Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -426,12 +426,16 @@ jobs:
run: bunx playwright install chromium
- name: Pack the published packages
run: bash scripts/pack-packages.sh --skip-build
- name: Test the app selection
run: bun test test/apps/selection.test.ts
- name: App scenarios
# Each app in test/apps installs from the tarballs above plus registry
# firebase, firebase-admin and vite, runs its own Vite dev server and
# server scripts, and drives its page in Chromium. npm downloads go to
# ~/.cache/pyric-app-scenarios-npm, the cache restored above.
run: bun test/apps/run.ts --packages dist/packages
# ~/.cache/pyric-app-scenarios-npm, the cache restored above. Apps that
# wait on real timeouts (`export const slow = true`) are skipped here,
# on pull requests and main alike; slow-scenarios.yml runs them.
run: bun test/apps/run.ts --packages dist/packages --skip-slow
- name: Upload app scenario logs
if: failure()
uses: actions/upload-artifact@v4
Expand Down
99 changes: 99 additions & 0 deletions .github/workflows/slow-scenarios.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# The app scenarios that wait on real timeouts: each `test/apps/<name>` whose
# scenario.ts exports `slow = true`. Build & Test skips them on every run
# (`--skip-slow`); this workflow runs only them, on the same packed packages.
#
# Runs on pushes to main, nightly, on demand, and on a pull request when the
# `ci-slow-scenarios` label is added (by someone with triage access). A push
# after the label does not run it again: remove and re-add the label, or
# re-run the workflow. It is not part of `CI / required`.

name: Slow app scenarios

on:
push:
branches: [main]
schedule:
- cron: '47 9 * * *'
pull_request:
types: [labeled]
workflow_dispatch:
inputs:
scenario:
description: 'One app under test/apps to run, slow or not. Empty runs every slow app.'
required: false
default: ''

permissions:
contents: read

concurrency:
# One run per ref; a newer one cancels it. Adding any other label to a pull
# request starts a run that does nothing, so it gets a group of its own
# instead of cancelling a slow run in progress.
group: slow-scenarios-${{ github.ref }}${{ github.event_name == 'pull_request' && github.event.label.name != 'ci-slow-scenarios' && format('-{0}', github.run_id) || '' }}
cancel-in-progress: true

jobs:
slow-scenarios:
name: Slow app scenarios (real apps on the packed packages)
runs-on: ubuntu-latest
timeout-minutes: 30
if: github.event_name != 'pull_request' || github.event.label.name == 'ci-slow-scenarios'
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
with:
bun-version: '1.3.11'
- name: Cache Bun dependencies
uses: actions/cache@v4
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- uses: actions/setup-node@v4
with:
node-version: '22.15'
- name: Cache app npm downloads
uses: actions/cache@v4
with:
path: ~/.cache/pyric-app-scenarios-npm
key: app-scenarios-npm-${{ runner.os }}-${{ hashFiles('test/apps/*/package.json', 'packages/*/package.json') }}
restore-keys: app-scenarios-npm-${{ runner.os }}-
- name: Install
run: bun install --frozen-lockfile --filter '!@pyric/playground'
# Restores the build Build & Test saved for these inputs, or builds the
# packages (scripts/build.sh --packages-only) and saves them.
- uses: ./.github/actions/restore-dist
with:
flavor: packages
- name: Cache Playwright Chromium
id: playwright-cache
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-chromium-${{ runner.os }}-${{ env.ImageOS }}-${{ hashFiles('packages/cli/package.json', 'package.json') }}
restore-keys: |
playwright-chromium-${{ runner.os }}-${{ env.ImageOS }}-
playwright-chromium-${{ runner.os }}-
- name: Install Chromium browser
run: bunx playwright install chromium
- name: Pack the published packages
run: bash scripts/pack-packages.sh --skip-build
- name: Slow app scenarios
env:
SCENARIO: ${{ github.event.inputs.scenario }}
run: |
if [ -n "$SCENARIO" ]; then
bun test/apps/run.ts --packages dist/packages "$SCENARIO"
else
bun test/apps/run.ts --packages dist/packages --only-slow
fi
- name: Upload app scenario logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: slow-app-scenarios-logs-${{ github.run_attempt }}
path: test-results/apps/
if-no-files-found: warn
retention-days: 7
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ Passing a unit test or MRE oracle is necessary but not sufficient. Before openin
4. **Foundation Reuse (`pyric/sandbox/internal`):** Never duplicate cross-service logic (auth normalization, path canonicalization, error shapes) inside a single service package. Reuse or extend the shared sandbox foundation.
5. **Cross-Runtime Fallback Verification:** In dual-runtime utilities (e.g., `typeof Buffer === 'function'` vs. browser `btoa`), `bun test` only hits the Node/Bun branch by default. Explicitly test the browser/worker branch by temporarily deleting the Node global (e.g., `delete (globalThis as any).Buffer`) and asserting parity across boundary cases (empty payloads, padding remainders).
6. **Conformance Registry Per-Service Count Invariant:** Every assurance node belongs to one service: a row in `packages/conformance/registry/<service>.ts`, or a construct in `packages/conformance/rules-language/<engine>.json` (service `<engine>-rules`). Each service commits its node count in `packages/conformance/assurance-node-counts/<service>.json`, and `packages/conformance/test/src/conformance-model.test.ts` fails when a service's derived count differs from that file, naming the service and the file. Adding or removing a row is a deliberate edit to that one service's count file in the same change; a new service adds its file and a removed service deletes its file. Run that test whenever registry rows or rules-language constructs change.
7. **Integration Evidence Through Real Entry Points:** A test that builds the payload, injects the frame, fakes the socket, mocks the timers, or passes a file in memory is unit evidence, however much real code it runs. A fix for a bug reported from a real app adds or extends an app scenario under `test/apps/` that installs the packed packages and drives the path the report took: the dev server, a `node --import @pyric/cli/register` process, Chromium, and the `pyric` command the user ran. Write it from the report, run it against `main` first, and record that failure in the commit body. A new feature reachable from a page, a server process, or the CLI gets the same scenario. When a bug's premise depends on runtime behavior (a browser lifecycle, a socket close, a restart), observe it in that runtime before fixing it; Playwright's defaults disable some of them, such as the back-forward cache. Every PR body names its integration test, or states why the change has no runtime path.
7. **Integration Evidence Through Real Entry Points:** A test that builds the payload, injects the frame, fakes the socket, mocks the timers, or passes a file in memory is unit evidence, however much real code it runs. A fix for a bug reported from a real app adds or extends an app scenario under `test/apps/` that installs the packed packages and drives the path the report took: the dev server, a `node --import @pyric/cli/register` process, Chromium, and the `pyric` command the user ran. Write it from the report, run it against `main` first, and record that failure in the commit body. A new feature reachable from a page, a server process, or the CLI gets the same scenario. When a bug's premise depends on runtime behavior (a browser lifecycle, a socket close, a restart), observe it in that runtime before fixing it; Playwright's defaults disable some of them, such as the back-forward cache. Every PR body names its integration test, or states why the change has no runtime path. A scenario that waits on real timeouts exports `slow = true` from its `scenario.ts`: pull requests skip it, and it runs on main, nightly, and on pull requests labeled `ci-slow-scenarios`. A PR that changes what a slow scenario covers gets that label and names the run.

10 changes: 10 additions & 0 deletions test/apps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,18 @@ bun test/apps/run.ts hosted-dev-server-restart
bun test/apps/run.ts --build # rebuild the workspace before packing it
bun test/apps/run.ts --packages dist/packages # install these tarballs instead of packing
bun test/apps/run.ts --keep # keep each installed app directory
bun test/apps/run.ts --skip-slow # leave out the slow apps
bun test/apps/run.ts --only-slow # run only the slow apps
```

A scenario that waits on real timeouts, such as a liveness window, marks itself slow next to its default export:

```ts
export const slow = true;
```

Build & Test runs the app scenarios with `--skip-slow`, on pull requests and on main. The Slow app scenarios workflow (`.github/workflows/slow-scenarios.yml`) runs them with `--only-slow` on pushes to main, nightly, on demand, and on a pull request when the `ci-slow-scenarios` label is added. An app named on the command line runs whether or not it is slow. The runner imports each `scenario.ts` to read the marker before installing anything, so a scenario imports only the driver, Playwright, and node built-ins at its top level.

npm downloads are cached in `~/.cache/pyric-app-scenarios-npm` (set `PYRIC_APPS_NPM_CACHE` to move it), so a second run installs in seconds. Without `--packages`, the runner packs the current workspace build. Run `bun run build` first, or pass `--build`. Install Chromium once with `bunx playwright install chromium`.

A failure names the app and the step, and prints the dev server log, each server script's output, and the browser console. Full logs are saved to `test-results/apps/<name>/`.
Expand Down
3 changes: 3 additions & 0 deletions test/apps/host-closes-silent-page/scenario.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ import { scenario, sleep } from '../driver.ts';
declare const presence: { goOnline(user: string): Promise<void>; read(user: string): Promise<unknown> };
declare const restoredFromCache: boolean | undefined;

/** Waits out a 40s liveness window and a heartbeat past it, so pull requests skip it (test/apps/selection.ts). */
export const slow = true;

const WINDOW_MS = 40_000;
const HEARTBEAT_MS = 15_000;

Expand Down
64 changes: 37 additions & 27 deletions test/apps/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@
* --build build the workspace before packing it
* --jobs <n> apps run at once (default 3)
* --keep keep each app's installed directory
* --skip-slow leave out the apps whose scenario.ts exports `slow = true`
* --only-slow run only those apps
*
* A slow app waits on real timeouts. Pull requests skip it; the "Slow app
* scenarios" workflow runs it. An app named on the command line runs either
* way.
*
* Without --packages, the runner packs the current workspace build into
* dist/packages. Logs land in test-results/apps/<name>/.
Expand All @@ -23,42 +29,37 @@ import { homedir, tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { AppRun, StepFailure, type Scenario } from './driver.ts';
import { installApp, packWorkspace, tarballsIn, type Tarballs } from './install.ts';
import { parseArguments, selectApps, skippedSlowClause } from './selection.ts';

const appsDir = import.meta.dir;
const root = resolve(appsDir, '../..');
const resultsDir = join(root, 'test-results/apps');
const APP_TIMEOUT_MS = Number(process.env.PYRIC_APP_TIMEOUT_MS ?? 300_000);
const LOG_TAIL_LINES = 200;

interface Options {
names: string[];
packages?: string;
build: boolean;
jobs: number;
keep: boolean;
}

function parseArguments(argv: string[]): Options {
const options: Options = { names: [], build: false, jobs: 3, keep: false, packages: process.env.PYRIC_PACKAGE_ARTIFACT_DIR };
for (let index = 0; index < argv.length; index++) {
const argument = argv[index]!;
if (argument === '--build') options.build = true;
else if (argument === '--keep') options.keep = true;
else if (argument === '--packages') options.packages = argv[++index];
else if (argument === '--jobs') options.jobs = Math.max(1, Number(argv[++index]));
else if (argument.startsWith('--')) throw new Error(`unknown option ${argument}`);
else options.names.push(argument);
}
return options;
}

function discoverApps(): string[] {
return readdirSync(appsDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && existsSync(join(appsDir, entry.name, 'scenario.ts')))
.map((entry) => entry.name)
.sort();
}

interface ScenarioModule {
default?: Scenario;
/** True for a scenario that waits on real timeouts. */
slow?: boolean;
}

function loadScenario(name: string): Promise<ScenarioModule> {
return import(join(appsDir, name, 'scenario.ts')) as Promise<ScenarioModule>;
}

/** The apps whose scenario.ts exports `slow = true`. Each scenario imports only the driver, Playwright, and node built-ins. */
async function slowApps(names: readonly string[]): Promise<Set<string>> {
const modules = await Promise.all(names.map(async (name) => ({ name, module: await loadScenario(name) })));
return new Set(modules.filter(({ module }) => module.slow === true).map(({ name }) => name));
}

interface AppResult {
name: string;
ok: boolean;
Expand Down Expand Up @@ -108,7 +109,7 @@ async function runApp(name: string, context: {
logs.push({ name: 'npm install', text: install.output });
if (install.code !== 0) throw new StepFailure('npm install', new Error(`npm install exited with code ${install.code}`));
run.currentStep = 'load scenario';
const module = await import(join(appsDir, name, 'scenario.ts')) as { default?: Scenario };
const module = await loadScenario(name);
if (typeof module.default !== 'function') throw new StepFailure('load scenario', new Error('scenario.ts has no default export from scenario()'));
await withTimeout(module.default(run), APP_TIMEOUT_MS, run);
const hostErrors = run.unexpectedHostErrors();
Expand Down Expand Up @@ -173,14 +174,22 @@ async function pool<T, R>(items: T[], size: number, work: (item: T) => Promise<R
}

async function main(): Promise<void> {
const options = parseArguments(process.argv.slice(2));
const options = parseArguments(process.argv.slice(2), process.env);
const available = discoverApps();
const unknown = options.names.filter((name) => !available.includes(name));
if (unknown.length) {
console.error(`unknown app: ${unknown.join(', ')}\napps: ${available.join(', ')}`);
process.exit(2);
}
const names = options.names.length ? options.names : available;
const filtersSlow = options.slow !== 'include' && options.names.length === 0;
const slow = filtersSlow ? await slowApps(available) : new Set<string>();
const { run: names, skippedSlow } = selectApps({ available, names: options.names, slow, filter: options.slow });
if (names.length === 0) {
// A run that drives no app passes without proving anything, so a marker
// removed by mistake fails the slow workflow instead of turning it green.
console.error(`no app is selected (${options.slow === 'only' ? 'no scenario.ts exports slow = true' : 'every app is slow'})`);
process.exit(2);
}
const started = performance.now();

let tarballs: Tarballs;
Expand Down Expand Up @@ -209,9 +218,10 @@ async function main(): Promise<void> {
const failed = results.filter((result) => !result.ok);
const total = ((performance.now() - started) / 1000).toFixed(1);
console.log('');
const skipped = skippedSlowClause(skippedSlow);
console.log(failed.length
? `✗ ${failed.length} of ${results.length} apps failed (${total}s): ${failed.map((result) => `${result.name} at "${result.step}"`).join(', ')}`
: `✓ ${results.length} apps passed (${total}s)`);
? `✗ ${failed.length} of ${results.length} apps failed (${total}s): ${failed.map((result) => `${result.name} at "${result.step}"`).join(', ')}${skipped}`
: `✓ ${results.length} apps passed (${total}s)${skipped}`);
process.exit(failed.length ? 1 : 0);
}

Expand Down
63 changes: 63 additions & 0 deletions test/apps/selection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, expect, test } from 'bun:test';
import { parseArguments, selectApps, skippedSlowClause } from './selection.ts';

const available = ['admin-writes', 'host-closes-silent-page', 'hosted-restart'];
const slow = new Set(['host-closes-silent-page']);

describe('slow app selection', () => {
test('--skip-slow leaves the slow apps out and reports them', () => {
expect(selectApps({ available, names: [], slow, filter: 'skip' })).toEqual({
run: ['admin-writes', 'hosted-restart'],
skippedSlow: ['host-closes-silent-page'],
});
});

test('--only-slow runs the slow apps alone', () => {
expect(selectApps({ available, names: [], slow, filter: 'only' })).toEqual({
run: ['host-closes-silent-page'],
skippedSlow: [],
});
});

test('without a slow flag every app runs', () => {
expect(selectApps({ available, names: [], slow, filter: 'include' }).run).toEqual(available);
});

test('a named app runs whatever its marker says', () => {
expect(selectApps({ available, names: ['host-closes-silent-page'], slow, filter: 'skip' })).toEqual({
run: ['host-closes-silent-page'],
skippedSlow: [],
});
expect(selectApps({ available, names: ['admin-writes'], slow, filter: 'only' }).run).toEqual(['admin-writes']);
});

test('the summary names the skipped apps, and says nothing when none were skipped', () => {
expect(skippedSlowClause(['host-closes-silent-page'])).toBe('; skipped 1 slow app (host-closes-silent-page)');
expect(skippedSlowClause(['a', 'b'])).toBe('; skipped 2 slow apps (a, b)');
expect(skippedSlowClause([])).toBe('');
});
});

describe('runner options', () => {
test('the slow flags set the filter', () => {
expect(parseArguments([]).slow).toBe('include');
expect(parseArguments(['--skip-slow']).slow).toBe('skip');
expect(parseArguments(['--only-slow', '--packages', 'dist/packages']).slow).toBe('only');
});

test('--skip-slow and --only-slow together are refused', () => {
expect(() => parseArguments(['--skip-slow', '--only-slow'])).toThrow('cannot be used together');
});

test('names, packages and the package directory from the environment still parse', () => {
const options = parseArguments(['--jobs', '2', 'hosted-restart'], { PYRIC_PACKAGE_ARTIFACT_DIR: 'out' });
expect(options).toMatchObject({ names: ['hosted-restart'], jobs: 2, packages: 'out', slow: 'include' });
});
});

describe('the slow markers in test/apps', () => {
test('host-closes-silent-page waits on its liveness window, so it is marked slow', async () => {
const module = await import('./host-closes-silent-page/scenario.ts') as { slow?: unknown };
expect(module.slow).toBe(true);
});
});
Loading
Loading