diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa72570c..1770ab40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,10 +4,12 @@ name: CI # changes decides whether the pull request needs the browser suites # (not while it is a draft, nor for docs-only changes), and # fetches the shard timings from the latest green main run -# checks Biome, ESLint, typecheck, unit tests, production build -# e2e the Playwright chromium and library projects in 3 shards, +# checks Biome, ESLint, typecheck, unit tests (parallel), production +# build +# e2e the Playwright chromium and library projects in 4 shards, # against `next dev` + Hocuspocus and the library's Bun harness -# perf the typing-budget project on its own runner, one worker +# perf the perf project in two jobs, each on its own runner with one +# worker: the typing budget, and the feature budgets # desktop the desktop static export and the local (dev bridge) project; # not a required check # e2e-gate "Playwright (Chromium)": merges the shard reports and passes @@ -121,7 +123,11 @@ jobs: timings=$(jq -c . "$RUNNER_TEMP/timings/e2e-timings.json") || timings="" fi echo "timings=$timings" >> "$GITHUB_OUTPUT" - echo "Shard timings from run ${run:-none}: ${timings:+found}${timings:-none}" + if [ -n "$timings" ]; then + echo "Shard timings: $(jq length <<< "$timings") files, from run $run" + else + echo "Shard timings: none (latest green run: ${run:-none})" + fi checks: name: Lint, typecheck, unit tests, build @@ -174,15 +180,14 @@ jobs: - name: Typecheck run: bun run typecheck - # `bun run test` skips the stress probe; it runs below as a non-gating - # benchmark. + # Every file with `bun test --parallel`, then the files that assert a + # wall-clock budget serially (scripts/unit-tests.ts). The repository + # variable UNIT_SERIAL=1 runs them all serially instead. The stress + # probe runs nightly. - name: Unit tests - run: bun run test - - # Shared runners vary in speed, so a miss here is reported, not fatal. - - name: Stress benchmark (informational) - continue-on-error: true - run: bun run test:stress + env: + UNIT_SERIAL: ${{ vars.UNIT_SERIAL }} + run: bun scripts/unit-tests.ts - name: Production build run: bun run build @@ -193,7 +198,7 @@ jobs: run: bun scripts/check-editor-chunk-size.ts e2e: - name: Playwright shard ${{ matrix.shard }}/3 + name: Playwright shard ${{ matrix.shard }}/4 needs: changes if: needs.changes.outputs.e2e == 'true' runs-on: ubuntu-latest @@ -204,7 +209,7 @@ jobs: # Every shard reports, so one failure does not hide another. fail-fast: false matrix: - shard: [1, 2, 3] + shard: [1, 2, 3, 4] env: &e2e-env # Same raised limits as playwright.config.ts: three workers open many # sockets and documents from one IP. @@ -266,7 +271,7 @@ jobs: SHARD: ${{ matrix.shard }} run: | printf '%s' "$TIMINGS" > "$RUNNER_TEMP/e2e-timings.json" - args=$(bun scripts/e2e-shards.ts plan "$SHARD/3" \ + args=$(bun scripts/e2e-shards.ts plan "$SHARD/4" \ "$RUNNER_TEMP/e2e-timings.json" "$RUNNER_TEMP/shard-tests.txt") echo "args=$args" >> "$GITHUB_OUTPUT" @@ -303,13 +308,25 @@ jobs: retention-days: 7 perf: - name: Playwright perf (typing budget) + name: Playwright perf (${{ matrix.suite }}) needs: changes if: needs.changes.outputs.e2e == 'true' runs-on: ubuntu-latest timeout-minutes: 20 permissions: contents: read + strategy: + fail-fast: false + # The typing budget (performance, toolbar-perf) is one job; every other + # spec of the perf project is the other, so a new perf spec lands there. + matrix: + include: + - suite: typing budget + select: --test-list + key: perf-typing + - suite: features + select: --test-list-invert + key: perf-features env: *e2e-env steps: - *checkout @@ -319,21 +336,25 @@ jobs: - *install-chromium - *start-dev-servers - # The typing budget compares timings, so it gets a runner of its own - # and one worker (the project's setting). --no-deps: the project - # depends on chromium, which the shards run. + # Budgets compare timings, so each job gets a runner of its own and + # one worker (the project's setting). --no-deps: the project depends + # on chromium, which the shards run. - name: Run Playwright env: - PLAYWRIGHT_BLOB_OUTPUT_NAME: report-perf.zip - run: >- - CI="" bun playwright test --project=perf --no-deps --retries=1 - --trace off --reporter=list,blob + PLAYWRIGHT_BLOB_OUTPUT_NAME: report-${{ matrix.key }}.zip + SELECT: ${{ matrix.select }} + run: | + printf '%s\n' performance.spec.ts toolbar-perf.spec.ts \ + > "$RUNNER_TEMP/typing-budget.txt" + CI="" bun playwright test --project=perf --no-deps \ + "$SELECT=$RUNNER_TEMP/typing-budget.txt" --retries=1 \ + --trace off --reporter=list,blob - name: Upload blob report if: ${{ !cancelled() }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: blob-report-perf + name: blob-report-${{ matrix.key }} path: blob-report/ if-no-files-found: ignore retention-days: 1 @@ -342,7 +363,7 @@ jobs: if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: e2e-results-perf + name: e2e-results-${{ matrix.key }} path: | test-results/ ${{ runner.temp }}/dev.log @@ -485,13 +506,19 @@ jobs: fi # Green pushes to main only: the shard timings the next runs pack by. + # Averaged with the timings this run packed by (the changes job's + # output, from the previous green push), so one noisy run moves the + # plan only halfway. - name: Write shard timings if: success() && github.event_name == 'push' && github.ref == 'refs/heads/main' env: PLAYWRIGHT_JSON_OUTPUT_NAME: ${{ runner.temp }}/report.json + PREVIOUS: ${{ needs.changes.outputs.timings }} run: | bun playwright merge-reports --reporter=json all-blob-reports - bun scripts/e2e-shards.ts timings "$RUNNER_TEMP/report.json" e2e-timings.json + printf '%s' "$PREVIOUS" > "$RUNNER_TEMP/previous-timings.json" + bun scripts/e2e-shards.ts timings "$RUNNER_TEMP/report.json" \ + e2e-timings.json "$RUNNER_TEMP/previous-timings.json" - name: Publish shard timings if: success() && github.event_name == 'push' && github.ref == 'refs/heads/main' diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 6bc3959d..91e22ede 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -11,6 +11,9 @@ name: Nightly # from 3 clients against Hocuspocus (spec §7 abuse soak) # mixed-version N+1, release N and pre-N clients on one document with # the gate env at its default (spec §3.1 N+1 ship gate) +# unit-runs the unit tests fully serial and as CI runs them (parallel, +# clock-budget files serial), compared file by file, then +# the stress probe (informational) # library-property the web library's multi-writer compaction property # test (web library §2.5, W-D3) at 50,000 runs, seeded # from the run id; a failure prints the seed to replay @@ -364,6 +367,49 @@ jobs: if-no-files-found: ignore retention-days: 7 + # CI runs the unit tests with --parallel (scripts/unit-tests.ts). Here a + # fully serial run checks it: a file whose counts differ fails the night. + unit-runs: + name: Unit tests, serial vs parallel; stress probe + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version-file: .tool-versions + + - name: Install + run: bun install --frozen-lockfile + + - name: Unit tests (serial) + run: | + mkdir -p "$RUNNER_TEMP/unit" + bun run test --reporter=junit --reporter-outfile="$RUNNER_TEMP/unit/all-serial.xml" + + - name: Unit tests (as CI runs them) + if: ${{ !cancelled() }} + run: bun scripts/unit-tests.ts --junit "$RUNNER_TEMP/unit" + + - name: Compare serial and parallel + if: ${{ !cancelled() }} + run: >- + bun scripts/compare-unit-runs.ts "$RUNNER_TEMP/unit/all-serial.xml" + "$RUNNER_TEMP/unit/parallel.xml" "$RUNNER_TEMP/unit/serial.xml" + + # Shared runners vary in speed, so a miss here is reported, not fatal. + - name: Stress benchmark (informational) + if: ${{ !cancelled() }} + continue-on-error: true + run: bun run test:stress + library-property: name: Web library compaction property (50,000 runs) runs-on: ubuntu-latest diff --git a/AGENTS.md b/AGENTS.md index df49a38f..dbd314f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,5 +56,5 @@ - Heading stack extensions (fold, filter, drag, scale) should stay cleanly bounded so other Tiptap apps can adopt them without pulling in the full `components/document-editor` shell - Document schema enforces title-first (`heading block*`), heading levels 1-6, and title-scoped paste handling; empty docs are seeded when the Yjs fragment is empty after a server sync - Editor uses the `@docs.plus/extension-*` packages (Hyperlink, InlineCode, Indent, Placeholder, Mermaid, HyperMultimediaKit) in place of StarterKit `link`/`code`, `@tiptap/extensions` Placeholder and `@tiptap/extension-image`; mark names are `hyperlink` and `inlineCode` (legacy `link`/`code` in stored Yjs docs are renamed server-side in Hocuspocus `afterLoadDocument`); the extensions render their own popovers/toolbars, so `tiptap-ui` only adds toolbar triggers; `.github/workflows/docs-plus-extensions.yml` refreshes them daily (04:17 UTC) via PR -- CI: `.github/workflows/ci.yml` runs on PRs, the merge queue (`merge_group`) and pushes to `main`; only PR runs are cancelled by a newer push (a started `main` run always finishes and can deploy). Required checks (ruleset names, keep stable): `Lint, typecheck, unit tests, build` (`bun audit --audit-level=high`, Biome, ESLint, typecheck, unit tests without `tests/unit/stress`, build, editor chunk size) and `Playwright (Chromium)`, an always-run gate job that merges blob reports and needs `Playwright shard 1/3`–`3/3` (`make dev`, warm-up, the library harness, `CI= bun playwright test --project=chromium --project=library --test-list= --retries=1`, files packed by duration by `scripts/e2e-shards.ts` from the `e2e-timings` artifact that only green pushes to `main` publish, falling back to `--shard=N/3`) and `Playwright perf (typing budget)` (`--project=perf --no-deps`, own runner, one worker); the `desktop` job (`Desktop renderer (export and local)`, not required) runs the desktop export and `local` projects; draft PRs and PRs touching only `docs/**` or `*.md` (not `desktop/**`) skip the shards, perf and `desktop` via the `Changed files` job and still pass the gate, which fails closed on any skip in the merge queue, on `main` or on a ready PR (`ready_for_review` starts the full run); open PRs as drafts until ready; `tests/unit/ci/ci-workflow.test.ts` pins this shape; the stress probe is a non-blocking timing benchmark; `tests/unit/ci/workflow-permissions.test.ts` requires explicit read-only job permissions, `persist-credentials: false` and SHA-pinned actions in every workflow, and no checkout plus a success-and-push `if` in `workflow_run` workflows; `.github/workflows/nightly.yml` (03:41 and 08:00 UTC and on demand) runs the `pwa` project on a production build, yjs-soak, quick soaks and the load harness; deploys: `.github/workflows/deploy.yml` (`workflow_run` after CI succeeds on a push to `main` when the `AUTO_DEPLOY` repo variable is `on`, plus manual `gh workflow run deploy.yml`; it refuses commits not on `main` or without green CI, then SSHes to the host whose key can only run `scripts/deploy.sh`: build in a second checkout, restart Hocus, swap `.next`, auto-revert if Next.js does not answer, then `startOrRestart` `editor-purge`; PM2 restarts use `ecosystem.config.cjs --update-env`, so production env lives in that file; see `docs/operations/deploy-runbook.md`); `.github/workflows/desktop-shell.yml` (3-OS installers and `electron` specs) runs on every PR and the merge queue behind its own always-run `Desktop shell (gate)` check (builds only for ready PRs touching its paths; always in the merge queue, nightly and on demand; fails closed), pinned by `tests/unit/ci/desktop-shell-workflow.test.ts`; releases: push a `vX.Y.Z` tag on `main` and `.github/workflows/release.yml` publishes the GitHub release (generated PR list + CHANGELOG link); the docs.plus update workflow starts CI on its branch with `gh workflow run` (bot-made PRs start no workflows, and CI is a required check) +- CI: `.github/workflows/ci.yml` runs on PRs, the merge queue (`merge_group`) and pushes to `main`; only PR runs are cancelled by a newer push (a started `main` run always finishes and can deploy). Required checks (ruleset names, keep stable): `Lint, typecheck, unit tests, build` (`bun audit --audit-level=high`, Biome, ESLint, typecheck, unit tests via `bun scripts/unit-tests.ts`: `--parallel` except the clock-budget `SERIAL_FILES`, which run serially after; repo variable `UNIT_SERIAL=1` makes it all serial; no `tests/unit/stress`, which runs nightly with a serial-vs-parallel comparison; build, editor chunk size) and `Playwright (Chromium)`, an always-run gate job that merges blob reports and needs `Playwright shard 1/4`–`4/4` (`make dev`, warm-up, the library harness, `CI= bun playwright test --project=chromium --project=library --test-list= --retries=1`, files packed by duration by `scripts/e2e-shards.ts` from the `e2e-timings` artifact that only green pushes to `main` publish, falling back to `--shard=N/4`) and `Playwright perf (typing budget)` / `Playwright perf (features)` (`--project=perf --no-deps`, each on its own runner with one worker; typing budget is `performance` and `toolbar-perf` via `--test-list`, features is the rest via `--test-list-invert`); the `desktop` job (`Desktop renderer (export and local)`, not required) runs the desktop export and `local` projects; draft PRs and PRs touching only `docs/**` or `*.md` (not `desktop/**`) skip the shards, perf and `desktop` via the `Changed files` job and still pass the gate, which fails closed on any skip in the merge queue, on `main` or on a ready PR (`ready_for_review` starts the full run); open PRs as drafts until ready; `tests/unit/ci/ci-workflow.test.ts` pins this shape; the stress probe is a non-blocking timing benchmark that runs nightly (`unit-runs`); `tests/unit/ci/workflow-permissions.test.ts` requires explicit read-only job permissions, `persist-credentials: false` and SHA-pinned actions in every workflow, and no checkout plus a success-and-push `if` in `workflow_run` workflows; `.github/workflows/nightly.yml` (03:41 and 08:00 UTC and on demand) runs the `pwa` project on a production build, yjs-soak, quick soaks and the load harness; deploys: `.github/workflows/deploy.yml` (`workflow_run` after CI succeeds on a push to `main` when the `AUTO_DEPLOY` repo variable is `on`, plus manual `gh workflow run deploy.yml`; it refuses commits not on `main` or without green CI, then SSHes to the host whose key can only run `scripts/deploy.sh`: build in a second checkout, restart Hocus, swap `.next`, auto-revert if Next.js does not answer, then `startOrRestart` `editor-purge`; PM2 restarts use `ecosystem.config.cjs --update-env`, so production env lives in that file; see `docs/operations/deploy-runbook.md`); `.github/workflows/desktop-shell.yml` (3-OS installers and `electron` specs) runs on every PR and the merge queue behind its own always-run `Desktop shell (gate)` check (builds only for ready PRs touching its paths; always in the merge queue, nightly and on demand; fails closed), pinned by `tests/unit/ci/desktop-shell-workflow.test.ts`; releases: push a `vX.Y.Z` tag on `main` and `.github/workflows/release.yml` publishes the GitHub release (generated PR list + CHANGELOG link); the docs.plus update workflow starts CI on its branch with `gh workflow run` (bot-made PRs start no workflows, and CI is a required check) - Testing stack is `bun test` (happy-dom preload; all files share one process, so `mock.module` spreads the real module and is followed by `await import()`, and import-time env goes through `importFresh()` + `resetModules()` in `afterEach`) + Playwright (+ Yjs load/soak harness); `EditorPage.waitForSync()` waits for `data-server-synced` (editable earlier from the device copy), and tests type at full speed: misplaced text means an app bug, not a missing wait; use `bun run test` (it skips the stress probe; `bun run test:stress` runs it), run Playwright with `CI=` against existing dev servers, and use `window.__HOCUS_URL`/`window.__HOCUS_TOKEN`/`window.__GLOBAL_TABS_DOC` hooks for test isolation; subprocesses that spawn `bun run hocus` for reconnect-heavy flows should set `HOCUS_THROTTLE=0` so official throttle does not false-positive ban clients; e2e hocus also needs `HOCUS_ALLOW_ISOLATED_TABS_DOCS=1` and raised socket limits (see `playwright.config.ts`), and `next dev` and hocus must share one `DB_PATH` (the DELETE route and Hocuspocus read the same tombstones); e2e needs `next dev` because helpers use `window.__tiptap_editor`; the `pwa` Playwright project runs only against a production build (`PWA_BASE_URL`); all other projects block service workers diff --git a/CHANGELOG.md b/CHANGELOG.md index ee7ce78d..80ed61fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -237,6 +237,71 @@ visible heading and `role="group"` with the same label, and every row keeps a there). Nothing is added or removed. Page width follows with the preferences work. Editor chunk +1 B against `main` at `84a9458`, from chunk-name hashes only; no eager code. +### CI: shard timings averaged across runs + +One run's per-file times are noisy (`mobile-bar.spec.ts` took 116 s in one +run and 263 s in the next), and a plan packed from a single run inherits +that noise, so a shard could carry 16% more than planned. + +#### Changed + +- **CI:** when a green push to `main` publishes `e2e-timings`, each file's + time is averaged with the timings that run packed by (an exponential + moving average, half weight to the newest run). A new spec keeps its own + time and a deleted one is dropped; without usable previous timings the + run's own are written, as before. +- **Tests:** `e2e-shards.test.ts` covers the average; `ci-workflow.test.ts` + pins that the publish step reads the timings the run packed by. + +**Deploy:** none. +### CI: four shards, two perf jobs and parallel unit tests + +The suite has grown to 627 browser tests (about 3,500 s), so three packed +shards still took about 8 minutes, perf took 7 and the checks job 5 (half +of it the serial unit tests and the informational stress probe). + +#### Changed + +- **CI:** the browser suites run in four duration-packed shards + (`Playwright shard 1/4` … `4/4`). +- **CI:** perf runs in two jobs, each on its own runner with one worker: + `Playwright perf (typing budget)` (`performance.spec.ts`, + `toolbar-perf.spec.ts`) and `Playwright perf (features)` (every other perf + spec, so a new one lands there). `Playwright (Chromium)` needs both. +- **CI:** unit tests run with `bun test --parallel` through + `scripts/unit-tests.ts`; the files that assert a wall-clock budget run + serially after them. The repository variable `UNIT_SERIAL=1` runs every + file serially. A parallel shadow run matched the serial one file by file + on 6 of 6 runs (#155, folded in here). +- **CI:** the stress probe moved from the checks job to the nightly + `unit-runs` job, which also runs the unit tests fully serially and as CI + runs them and compares the two file by file (`scripts/compare-unit-runs.ts`). +- **CI:** `Changed files` logs how many shard timings it found instead of + the whole JSON. +- **Tests:** `tests/unit/ci/unit-tests.test.ts` fails when a unit test with + a wall-clock budget is missing from the serial list; + `compare-unit-runs.test.ts`; `ci-workflow.test.ts` pins the four shards, + the perf split and the unit-test step; the nightly streak classifies the + new nightly steps as test steps. + +**Deploy:** none. **Owner:** each merge queue entry now runs about 17 jobs +(CI and the desktop shell), so the runbook recommends build concurrency +**1** instead of 2. + +### Desktop storage: a power cut loses only derived rows + +The condition on D-A6's amendment (derived rows commit at +`synchronous=NORMAL`). + +- **Tests:** `derive-crash-loss.test.ts` simulates a power cut after a + FULL append and a NORMAL derive, as a dropped last commit and as a torn + WAL tail. The append survives, the derived rows and `derived_seq` are + lost together, the document reads as stale, and the next derive + restores the rows. A control keeps the whole WAL and the derive. +- **Docs:** the architecture spec's D-A6 amendment records the approval + and points to the test. + +**Deploy:** none. ### Desktop P2.6f: repair and rebuild the library Repair and rebuild for the format-2 library (offline data-model revision diff --git a/docs/operations/deploy-runbook.md b/docs/operations/deploy-runbook.md index 0a1975a6..640cc9ff 100644 --- a/docs/operations/deploy-runbook.md +++ b/docs/operations/deploy-runbook.md @@ -173,7 +173,7 @@ must not change: | Check | Job | What it covers | | --- | --- | --- | | `Lint, typecheck, unit tests, build` | `checks` | audit, Biome, ESLint, typecheck, unit tests, production build, editor chunk size | -| `Playwright (Chromium)` | `e2e-gate` | passes only when the three `Playwright shard N/3` jobs and `Playwright perf (typing budget)` passed, or when the pull request changes only `docs/**` or Markdown files (outside `desktop/**`) and they were skipped | +| `Playwright (Chromium)` | `e2e-gate` | passes only when the four `Playwright shard N/4` jobs, `Playwright perf (typing budget)` and `Playwright perf (features)` passed, or when the pull request changes only `docs/**` or Markdown files (outside `desktop/**`) and they were skipped | The desktop shell workflow (`.github/workflows/desktop-shell.yml`) adds a third check for the ruleset: @@ -198,9 +198,11 @@ pull requests ahead of it, and merges only what passed. CI already runs on 1. Settings → Rules → Rulesets → **Protect main** → Add rule → **Require merge queue**: - Merge method: **Merge commit** (what `main` uses today). - - Build concurrency: **2** (each entry runs about seven jobs, and GitHub's - free plan runs 20 jobs at a time across the organisation: three entries - would take about 21, leaving nothing for pull requests). + - Build concurrency: **1** (each entry runs about 17 jobs: 11 of CI and + 6 of the desktop shell, and GitHub's free plan runs 20 jobs at a time + across the organisation, so two entries would leave nothing for pull + requests). The group fills in the wait below, so one entry still merges + several pull requests. - Merge limits: minimum **1**, maximum **5**; wait **1 minute** to fill a group, so pull requests queued together usually land as one push to `main`, one CI run and one deploy, without holding a lone one back. @@ -244,7 +246,7 @@ gh api repos/docs-plus/editor/rulesets/26847251 \ | jq '{name, target, enforcement, conditions, bypass_actors, rules: (.rules + [{type: "merge_queue", parameters: { merge_method: "MERGE", grouping_strategy: "ALLGREEN", - max_entries_to_build: 2, min_entries_to_merge: 1, + max_entries_to_build: 1, min_entries_to_merge: 1, max_entries_to_merge: 5, min_entries_to_merge_wait_minutes: 1, check_response_timeout_minutes: 60}}])}' \ | gh api -X PUT repos/docs-plus/editor/rulesets/26847251 --input - diff --git a/docs/superpowers/specs/2026-11-15-desktop-architecture.md b/docs/superpowers/specs/2026-11-15-desktop-architecture.md index c6a6b24d..7e27018a 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-architecture.md +++ b/docs/superpowers/specs/2026-11-15-desktop-architecture.md @@ -23,7 +23,7 @@ | D-A3 | **Compaction runs in the renderer.** It sends `encodeStateAsUpdate` plus the highest `seq` that state covers. The worker upserts the snapshot and deletes `seq ≤ X` in one transaction. Main keeps a **registry of open documents**, which replaces leases. Main and the worker write content only to documents that are not open. No `rev` compare-and-set. | The renderer already holds the merged state, so compaction costs one encode. This is correct **only because a document is open in at most one window** (§5.2). The web library can't enforce one tab per document, so its compaction merges into the stored snapshot and deletes only the rows its own session applied (web library W-D3). That rule needs no invariant, and desktop can adopt it later. | | D-A4 | **A thin `local-session`** (about 100 lines: load, apply, append, no timeouts) sits behind a `DocSession` interface, which `use-yjs-document` consumes. It and the batcher are platform-neutral (`lib/platform/local-session.ts`, `lib/platform/batcher.ts`), because the web library reuses them over IndexedDB (D3). The sandbox's `collab-session` is untouched except for the P1.1 and P1.1b fixes. The only shared editor changes: the provider becomes optional, and `document-editor.tsx` gets one stable y-protocols `Awareness`, under a byte allowance. (Live) The provider attaches on top of `local-session`. | Keeps the web path and its bundle as they are, and keeps desktop code small enough to read in one sitting. | | D-A5 | **Local-release tables:** `meta` (with the `prefs` row), `docs`, `snapshots`, `updates` (with an `origin` column), `folders`, `tags` and `doc_tags` (D7), `doc_view` (per-document width, continue position and remote-image consent, D10), and the asset index `blobs` and `doc_blobs` (D4; the bytes are files under `/assets/`). `remotes`, `versions`, `share_blobs` and pre-wipe snapshots come in the Live release. A lineage UUID is written at creation from day one; `.tinydoc` import (P2.8) reads it to match backups. `docs.schema` stays, with a minimal migration hook that runs after hydrate and before the editor binds, as forward edits outside undo. Today's legacy-mark migrations run at **import**. | Ships only what the Local release uses, and keeps the two columns that are expensive to backfill. | -| D-A6 | **Safety core:** WAL, `synchronous=FULL`, `fullfsync` on macOS, `quick_check` after an unclean exit, the `format_version` read-only guard, `VACUUM INTO` before every migration, and a daily `VACUUM INTO` keeping 7 copies. The daily copies are the Local release's restore points ("Restore from a daily snapshot"). | One mechanism covers both restore points and protection against corruption, with no `versions` table. **Confirmed by S2:** the pragmas read back as set on all three OSes (`wal`, `synchronous` 2, and on macOS `fullfsync` and `checkpoint_fullfsync` 1); on an Apple-silicon Mac a 4 KB commit takes 4.0 ms p50 with `fullfsync` against 0.13 ms without it, so F_FULLFSYNC reaches the drive. **Amended 2026-11-22 (soak T21, T4-copy):**
• Derived rows (`derive.put`, offline revision §4.3) commit at `synchronous=NORMAL`. They are a cache: a power cut loses the rows and their `derived_seq` together, so the document reads as stale and is derived again. Without the fsync, a read queued behind a derive no longer waits 4–10 ms for the disk. User content, identity and library state stay FULL.
• Every connection sets `busy_timeout` (3 s), so a lock held for a moment (on Windows, a scanner or a closing handle) waits instead of failing. TRUNCATE checkpoints run with no timeout, so a reader such as the daily copy never stretches a quit. | +| D-A6 | **Safety core:** WAL, `synchronous=FULL`, `fullfsync` on macOS, `quick_check` after an unclean exit, the `format_version` read-only guard, `VACUUM INTO` before every migration, and a daily `VACUUM INTO` keeping 7 copies. The daily copies are the Local release's restore points ("Restore from a daily snapshot"). | One mechanism covers both restore points and protection against corruption, with no `versions` table. **Confirmed by S2:** the pragmas read back as set on all three OSes (`wal`, `synchronous` 2, and on macOS `fullfsync` and `checkpoint_fullfsync` 1); on an Apple-silicon Mac a 4 KB commit takes 4.0 ms p50 with `fullfsync` against 0.13 ms without it, so F_FULLFSYNC reaches the drive. **Amended 2026-11-22 (soak T21, T4-copy):**
• Derived rows (`derive.put`, offline revision §4.3) commit at `synchronous=NORMAL`. They are a cache: a power cut loses the rows and their `derived_seq` together, so the document reads as stale and is derived again. Without the fsync, a read queued behind a derive no longer waits 4–10 ms for the disk. User content, identity and library state stay FULL.
• Every connection sets `busy_timeout` (3 s), so a lock held for a moment (on Windows, a scanner or a closing handle) waits instead of failing. TRUNCATE checkpoints run with no timeout, so a reader such as the daily copy never stretches a quit. **Proven by** `tests/unit/desktop/storage/derive-crash-loss.test.ts`: a power cut after a FULL append and a NORMAL derive, simulated as a dropped last commit and as a torn WAL tail, keeps the append and loses the derived rows with their `derived_seq`; the document reads as stale and the next derive restores the rows.| | D-A7 | **Readable backups:** changed documents are mirrored as `.tinydoc` plus `.md` into `~/TinyDocy Backups`, each written to a temp file and renamed. The renderer makes the Markdown on idle and on close with the existing Tiptap Markdown serializer and sends it to main. Retention is by count. | No DOM-free walker. Counting copies needs no clock-jump guard. | | D-A8 | **Search matches metadata only, never document body text. No FTS5** (owner D24, plan v7). Searched: titles, tags, folder names and document properties (dates, Local/Live, template kind), on desktop and in the web library. One shared normalizer (`lib/search/normalize.ts`: diacritics, Arabic→Persian letter folding, Persian/Arabic-Indic digits → ASCII; `Intl.Segmenter` only if titles need it) makes Quick Open and list filters accent- and case-insensitive. Metadata operators: `tag:`, `in:folder`, `is:live`. Rows with `kind='template'` are skipped. Full-text body search is later and not planned. Identity stays in `localStorage` (`tinydocy-user`, validated by F2: try/catch, a 32-grapheme name, an allowlisted colour) until P4.0 moves it into `meta('identity')`. | Cuts the walker, the FTS table, the text extractor and the identity migration from v1. Metadata is already in `docs`, `folders` and `doc_tags`, so search needs no new index. | | D-A9 | **Local-release ports:** `DocSession`, `DocStore`, `DocumentIndex`, `AppShell`, and `BlobStore` for images (D4). (Live) adds `SyncAttachment`, `ShareService` and `SecretStore`. Each port is chosen inside a composition-root component. The two roots are `app/page.tsx` and `app/page.desktop.tsx`, picked through `pageExtensions`: the desktop target lists only `desktop.tsx` and `desktop.ts`, so its routes are an allowlist and no file is moved for the export (§3.1, P2.4b). Hand-written guards run in main only. The IPC build version is checked at startup. The staged app folder holds CJS bundles made by Bun.build (S1 confirmed CJS; S3 packages it). | One literal decides the target. Neither build carries the other's import graph. The signed main bundle gets no validation dependency. | diff --git a/scripts/compare-unit-runs.ts b/scripts/compare-unit-runs.ts new file mode 100644 index 00000000..e8ef9024 --- /dev/null +++ b/scripts/compare-unit-runs.ts @@ -0,0 +1,101 @@ +// Compares `bun test --reporter=junit` reports file by file: a fully serial +// run against the run CI does (scripts/unit-tests.ts: a parallel report and +// a serial one for the clock-budget files, merged). Exits 1 when any file's +// passed, failed or skipped count differs. Nightly runs it (unit-runs). +// +// bun scripts/compare-unit-runs.ts serial.xml parallel.xml [more.xml …] + +import { readFileSync } from "node:fs"; + +export interface FileCounts { + passed: number; + failed: number; + skipped: number; +} + +export interface Report { + files: Map; + seconds: number; +} + +const attr = (tag: string, name: string) => + tag.match(new RegExp(`\\s${name}="([^"]*)"`))?.[1]; + +const count = (tag: string, name: string) => Number(attr(tag, name) ?? 0); + +// Bun writes one top-level per file, indented two spaces, with +// nested suites (describe blocks) indented further. +export const parseJunit = (xml: string): Report => { + const files = new Map(); + for (const [tag] of xml.matchAll(/^ {2}]*>/gm)) { + const file = attr(tag, "file") ?? attr(tag, "name") ?? ""; + const failed = count(tag, "failures") + count(tag, "errors"); + const skipped = count(tag, "skipped"); + files.set(file, { + passed: count(tag, "tests") - failed - skipped, + failed, + skipped, + }); + } + const root = xml.match(/]*>/)?.[0] ?? ""; + return { files, seconds: count(root, "time") }; +}; + +const show = (counts: FileCounts | undefined) => + counts + ? `${counts.passed} passed, ${counts.failed} failed, ${counts.skipped} skipped` + : "missing"; + +export const compareReports = (serial: Report, parallel: Report) => { + const differences: string[] = []; + const names = new Set([...serial.files.keys(), ...parallel.files.keys()]); + for (const name of [...names].sort()) { + const a = serial.files.get(name); + const b = parallel.files.get(name); + if ( + a?.passed !== b?.passed || + a?.failed !== b?.failed || + a?.skipped !== b?.skipped + ) { + differences.push(`${name}: serial ${show(a)}; parallel ${show(b)}`); + } + } + return differences; +}; + +/** One report from several, as from runs over disjoint sets of files. */ +export const mergeReports = (reports: Report[]): Report => ({ + files: new Map(reports.flatMap((report) => [...report.files])), + seconds: reports.reduce((sum, report) => sum + report.seconds, 0), +}); + +const total = (report: Report) => + [...report.files.values()].reduce((sum, file) => sum + file.passed, 0); + +if (import.meta.main) { + const [serialPath, ...parallelPaths] = process.argv.slice(2); + if (!serialPath || parallelPaths.length === 0) { + console.error( + "usage: compare-unit-runs.ts [more.xml …]", + ); + process.exit(2); + } + const serial = parseJunit(readFileSync(serialPath, "utf8")); + const parallel = mergeReports( + parallelPaths.map((path) => parseJunit(readFileSync(path, "utf8"))), + ); + console.log( + `serial: ${serial.files.size} files, ${total(serial)} passed, ${serial.seconds.toFixed(1)} s`, + ); + console.log( + `parallel: ${parallel.files.size} files, ${total(parallel)} passed, ${parallel.seconds.toFixed(1)} s`, + ); + const differences = compareReports(serial, parallel); + if (differences.length === 0) { + console.log("Per-file counts match."); + } else { + for (const line of differences) console.log(`::warning::${line}`); + console.log(`${differences.length} file(s) differ.`); + process.exit(1); + } +} diff --git a/scripts/e2e-shards.ts b/scripts/e2e-shards.ts index 1cacc577..b8356577 100644 --- a/scripts/e2e-shards.ts +++ b/scripts/e2e-shards.ts @@ -7,8 +7,10 @@ // Prints the Playwright arguments for this shard: `--test-list=` // after writing the shard's files there, or `--shard=/` // (Playwright's own split) when the timings are missing or invalid. -// bun scripts/e2e-shards.ts timings -// Writes per-file seconds from a merged Playwright JSON report. +// bun scripts/e2e-shards.ts timings [previous.json] +// Writes per-file seconds from a merged Playwright JSON report, averaged +// with the previous timings (when given and valid) so one slow or noisy +// run moves the plan only halfway. // // Every shard computes the same plan from the same inputs, so together // they run each spec file exactly once. @@ -107,6 +109,30 @@ export const timingsFromReport = (report: { suites?: ReportSuite[] }) => { return timings; }; +/** Weight of the newest run in {@link smoothTimings}. */ +export const SMOOTHING = 0.5; + +/** + * An exponential moving average per file: `weight` of the newest run plus + * the rest of the previous average. A file the newest run didn't time (a + * deleted spec) is dropped; a file with no previous time keeps its new one. + */ +export const smoothTimings = ( + current: Timings, + previous: Timings, + weight = SMOOTHING, +): Timings => + Object.fromEntries( + Object.entries(current).map(([file, seconds]) => { + const before = previous[file]; + const blended = + before === undefined + ? seconds + : weight * seconds + (1 - weight) * before; + return [file, Math.round(blended * 10) / 10]; + }), + ); + /** Spec files Playwright would run, relative to its rootDir. */ const listSpecFiles = (projects: string[]) => { const result = Bun.spawnSync( @@ -161,16 +187,30 @@ if (import.meta.main) { const [command, ...args] = process.argv.slice(2); if (command === "plan" && args.length === 3) { plan(args[0], args[1], args[2]); - } else if (command === "timings" && args.length === 2) { + } else if ( + command === "timings" && + (args.length === 2 || args.length === 3) + ) { const report = JSON.parse(readFileSync(args[0], "utf8")); - writeFileSync( - args[1], - `${JSON.stringify(timingsFromReport(report), null, 2)}\n`, - ); + let timings = timingsFromReport(report); + if (args[2]) { + try { + timings = smoothTimings( + timings, + parseTimings(readFileSync(args[2], "utf8")), + ); + console.error("e2e-shards: averaged with the previous timings"); + } catch (error) { + console.error( + `e2e-shards: no usable previous timings (${(error as Error).message}); writing this run's`, + ); + } + } + writeFileSync(args[1], `${JSON.stringify(timings, null, 2)}\n`); } else { console.error( "usage: e2e-shards.ts plan / \n" + - " e2e-shards.ts timings ", + " e2e-shards.ts timings [previous.json]", ); process.exit(2); } diff --git a/scripts/unit-tests.ts b/scripts/unit-tests.ts new file mode 100644 index 00000000..2c5105f1 --- /dev/null +++ b/scripts/unit-tests.ts @@ -0,0 +1,73 @@ +// The unit tests as CI runs them (tests/TESTING.md, "CI"): every file with +// `bun test --parallel`, except the ones that assert a wall-clock budget, +// which then run serially so no other file competes for the CPU. +// +// bun scripts/unit-tests.ts [--junit ] +// +// UNIT_SERIAL=1 runs everything serially instead (`bun run test`), the +// fallback if the parallel runner misbehaves. With --junit, each run writes +// a JUnit report into (parallel.xml and serial.xml, or all.xml). +// The stress probe (tests/unit/stress) is never included; it runs nightly. + +/** + * Unit test files that read the clock and assert a duration. Under + * --parallel they share the CPU with other files and can miss their + * budget, so they run serially. tests/unit/ci/unit-tests.test.ts fails on + * a timing test missing from this list. + */ +export const SERIAL_FILES = [ + "tests/unit/components/bubble-controller.test.ts", + "tests/unit/desktop/storage/busy-timeout.test.ts", + "tests/unit/extensions/find/find-hits.test.ts", + "tests/unit/helpers/spawn-hocus.test.ts", + "tests/unit/lib/links/extract-perf.test.ts", + "tests/unit/lib/markdown-parse.test.ts", + "tests/unit/lib/security/hocus-document-guard.test.ts", +] as const; + +export const STRESS = "tests/unit/stress/**"; + +const junit = (dir: string | undefined, name: string) => + dir ? ["--reporter=junit", `--reporter-outfile=${dir}/${name}.xml`] : []; + +/** The `bun test` invocations, in order. */ +export const plan = (serialOnly: boolean, junitDir?: string): string[][] => + serialOnly + ? [ + [ + "bun", + "test", + `--path-ignore-patterns=${STRESS}`, + ...junit(junitDir, "all"), + ], + ] + : [ + [ + "bun", + "test", + "--parallel", + `--path-ignore-patterns=${STRESS}`, + ...SERIAL_FILES.map((file) => `--path-ignore-patterns=${file}`), + ...junit(junitDir, "parallel"), + ], + ["bun", "test", ...junit(junitDir, "serial"), ...SERIAL_FILES], + ]; + +if (import.meta.main) { + const args = process.argv.slice(2); + const at = args.indexOf("--junit"); + const junitDir = at >= 0 ? args[at + 1] : undefined; + const serialOnly = process.env.UNIT_SERIAL === "1"; + if (serialOnly) console.log("UNIT_SERIAL=1: running every file serially"); + let failed = false; + // Both runs always go: a failure in the first still reports the second. + for (const command of plan(serialOnly, junitDir)) { + console.log(`$ ${command.join(" ")}`); + const result = Bun.spawnSync(command, { + stdout: "inherit", + stderr: "inherit", + }); + if (result.exitCode !== 0) failed = true; + } + process.exit(failed ? 1 : 0); +} diff --git a/tests/TESTING.md b/tests/TESTING.md index 11f06aa5..ce7aa317 100644 --- a/tests/TESTING.md +++ b/tests/TESTING.md @@ -609,11 +609,11 @@ Each client gets a unique identity token (`load-client-{i}-{docId}`). | Job | Runs | |---|---| | Changed files | Pull requests: decides whether the browser suites run (not on a draft; not when only docs or Markdown changed, from `gh api .../pulls/N/files`). Every run: reads the shard timings from the latest green push run on `main` | -| Lint, typecheck, unit tests, build | `bun audit`, `bun run check`, `bun run lint`, `bun run typecheck`, `bun run test`, `bun run build`, editor chunk size | -| Playwright shard 1/3, 2/3, 3/3 | `make dev`, a warm-up request per page, the library harness (`tests/harness/library/serve.ts`), then `bun scripts/e2e-shards.ts plan N/3` and `CI= bun playwright test --project=chromium --project=library --test-list= --retries=1` with a blob report | -| Playwright perf (typing budget) | the same servers on a runner of its own, then `CI= bun playwright test --project=perf --no-deps --retries=1` (one worker) | +| Lint, typecheck, unit tests, build | `bun audit`, `bun run check`, `bun run lint`, `bun run typecheck`, `bun scripts/unit-tests.ts` (unit tests in parallel, then the clock-budget files serially), `bun run build`, editor chunk size | +| Playwright shard 1/4 … 4/4 | `make dev`, a warm-up request per page, the library harness (`tests/harness/library/serve.ts`), then `bun scripts/e2e-shards.ts plan N/4` and `CI= bun playwright test --project=chromium --project=library --test-list= --retries=1` with a blob report | +| Playwright perf (typing budget), Playwright perf (features) | the same servers, each on a runner of its own, then `CI= bun playwright test --project=perf --no-deps --retries=1` (one worker): `performance.spec.ts` and `toolbar-perf.spec.ts` with `--test-list`, and every other perf spec with `--test-list-invert` of the same list, so a new perf spec lands in features | | Desktop renderer (export and local) | not required: `bun run build:desktop`, the `desktop` project on the served export, then the `local` project over the dev bridge (`next dev` on port 3926, no retries) | -| Playwright (Chromium) | the required check: merges the blob reports (`bun playwright merge-reports --reporter=github,html`), then passes only if every shard and perf passed, or they were skipped for a docs-only pull request | +| Playwright (Chromium) | the required check: merges the blob reports (`bun playwright merge-reports --reporter=github,html`), then passes only if every shard and both perf jobs passed, or they were skipped for a draft or docs-only pull request | - **Required checks:** the `main` ruleset requires `Lint, typecheck, unit tests, build` and `Playwright (Chromium)`; keep both names, and every @@ -633,16 +633,18 @@ Each client gets a unique identity token (`load-client-{i}-{docId}`). those two reasons. In the merge queue, on `main` and in manual runs every suite always runs, and `Playwright (Chromium)` fails if any was skipped. - **Shards:** `scripts/e2e-shards.ts` packs the `chromium` and `library` - spec files into three shards by duration (longest first, into the + spec files into four shards by duration (longest first, into the least-loaded shard; a new spec counts as the median), from per-file seconds that `Playwright (Chromium)` publishes as the `e2e-timings` - artifact on green pushes to `main` only. The `Changed files` job reads them + artifact on green pushes to `main` only, each file averaged half and half + with the timings that run packed by (one run's noise, such as a spec + taking twice as long on a slow runner, moves the plan only halfway). The `Changed files` job reads them once, so every shard packs the same plan; without usable timings (none yet, expired after 30 days, or invalid) every shard uses Playwright's own - `--shard=N/3`. Each browser job logs its runner's CPU before the suites. + `--shard=N/4`. Each browser job logs its runner's CPU before the suites. To run one shard locally: `CI= bun playwright test --project=chromium - --project=library --shard=2/3`, or plan it from a timings file with - `bun scripts/e2e-shards.ts plan 2/3 e2e-timings.json list.txt`. + --project=library --shard=2/4`, or plan it from a timings file with + `bun scripts/e2e-shards.ts plan 2/4 e2e-timings.json list.txt`. - **Shard balance:** Playwright's own `--shard` gives each shard a contiguous range of spec files sized by test *count*, so the specs with slow tests (palette, selection-bubble, paint-format, slash-menu, @@ -652,7 +654,22 @@ Each client gets a unique identity token (`load-client-{i}-{docId}`). `PWTEST_SHARD_WEIGHTS` drift or may vanish, so the shards are packed by measured time instead. The runner's CPU still varies shard times by about 40% (Intel Xeon 6975P vs AMD EPYC 7763). -- **Stress probe:** `bun run test:stress` runs as a separate step with +- **Unit tests in parallel:** `bun scripts/unit-tests.ts` runs every unit + file with `bun test --parallel` (about 26 s on CI against about 110 s + serially), then the files that read the clock and assert a budget + (`SERIAL_FILES`) serially, so no other file competes for the CPU. + `tests/unit/ci/unit-tests.test.ts` fails when a unit test with a + wall-clock budget is missing from that list. If the parallel runner + misbehaves, set the repository variable `UNIT_SERIAL=1` + (`gh variable set UNIT_SERIAL --body 1`) and CI runs every file serially, + as `bun run test` does locally; delete the variable to go back. Before + this ran in CI, a parallel shadow run matched the serial one file by file + on 6 of 6 runs. +- **Nightly checks of the parallel run:** the nightly `unit-runs` job runs + the unit tests fully serially and as CI runs them, and + `scripts/compare-unit-runs.ts` compares the JUnit reports file by file; a + file whose passed, failed or skipped count differs fails the night. +- **Stress probe:** `bun run test:stress` runs nightly (`unit-runs`), with `continue-on-error`. It measures transaction time, so a slow shared runner can miss its threshold without the code being wrong. - **Retries:** a test that passes on retry is listed as "flaky" in the diff --git a/tests/unit/ci/ci-workflow.test.ts b/tests/unit/ci/ci-workflow.test.ts index db50ccfd..67144e69 100644 --- a/tests/unit/ci/ci-workflow.test.ts +++ b/tests/unit/ci/ci-workflow.test.ts @@ -22,7 +22,13 @@ interface Job { permissions?: Record; if?: string; needs?: string | string[]; - strategy?: { "fail-fast"?: boolean; matrix?: { shard?: number[] } }; + strategy?: { + "fail-fast"?: boolean; + matrix?: { + shard?: number[]; + include?: { suite: string; select: string; key: string }[]; + }; + }; steps?: Step[]; } @@ -90,7 +96,7 @@ describe("CI workflow", () => { it("shards the chromium project and reports every shard", () => { const e2e = jobs.e2e; - expect(e2e.strategy?.matrix?.shard).toEqual([1, 2, 3]); + expect(e2e.strategy?.matrix?.shard).toEqual([1, 2, 3, 4]); expect(e2e.strategy?.["fail-fast"]).toBe(false); const run = runOf(e2e, "Run Playwright"); expect(run).toContain("--project=chromium"); @@ -103,7 +109,7 @@ describe("CI workflow", () => { it("packs every shard from the one set of timings the changes job read", () => { const plan = jobs.e2e.steps?.find((step) => step.name === "Plan shard"); expect(plan?.run).toContain("scripts/e2e-shards.ts plan"); - expect(plan?.run).toContain('"$SHARD/3"'); + expect(plan?.run).toContain('"$SHARD/4"'); expect(plan?.env?.TIMINGS).toBe(`\${{ needs.changes.outputs.timings }}`); expect(plan?.env?.SHARD).toBe(`\${{ matrix.shard }}`); const shardArgs = jobs.e2e.steps?.find( @@ -131,6 +137,10 @@ describe("CI workflow", () => { ), ); expect(writers).toHaveLength(2); + // Averaged with the timings this run read, never written from a PR. + const write = writers.find((step) => step.name === "Write shard timings"); + expect(write?.env?.PREVIOUS).toBe(`\${{ needs.changes.outputs.timings }}`); + expect(write?.run).toContain("previous-timings.json"); for (const step of writers) expect(step.if).toBe(MAIN_ONLY); // No other job uploads the timings artifact. const uploads = Object.values(jobs).flatMap((job) => @@ -148,6 +158,31 @@ describe("CI workflow", () => { expect(run).not.toContain("--project=chromium"); }); + it("splits perf into the typing budget and everything else", () => { + expect(jobs.perf.name).toBe(`Playwright perf (\${{ matrix.suite }})`); + expect(jobs.perf.strategy?.["fail-fast"]).toBe(false); + const legs = jobs.perf.strategy?.matrix?.include ?? []; + expect(legs.map((leg) => [leg.suite, leg.select])).toEqual([ + ["typing budget", "--test-list"], + ["features", "--test-list-invert"], + ]); + // One list: the typing-budget job runs it, the features job the rest, + // so a new perf spec can never fall between them. + const run = runOf(jobs.perf, "Run Playwright"); + expect(run).toContain("performance.spec.ts toolbar-perf.spec.ts"); + expect(run).toContain('"$SELECT=$RUNNER_TEMP/typing-budget.txt"'); + expect(new Set(legs.map((leg) => leg.key)).size).toBe(2); + }); + + it("runs the unit tests in parallel, with a serial fallback", () => { + const unit = jobs.checks.steps?.find((step) => step.name === "Unit tests"); + expect(unit?.run).toBe("bun scripts/unit-tests.ts"); + expect(unit?.env?.UNIT_SERIAL).toBe(`\${{ vars.UNIT_SERIAL }}`); + // The stress probe runs nightly, not on every pull request. + const runs = (jobs.checks.steps ?? []).map((step) => step.run ?? ""); + expect(runs.some((run) => run.includes("test:stress"))).toBe(false); + }); + it("gates on every shard and perf, even when they fail or skip", () => { const gate = Object.values(jobs).find( (job) => job.name === "Playwright (Chromium)", diff --git a/tests/unit/ci/compare-unit-runs.test.ts b/tests/unit/ci/compare-unit-runs.test.ts new file mode 100644 index 00000000..7334d545 --- /dev/null +++ b/tests/unit/ci/compare-unit-runs.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "bun:test"; + +import { + compareReports, + mergeReports, + parseJunit, +} from "../../../scripts/compare-unit-runs"; + +const report = ( + files: [string, number, number, number][], + time = 1.5, +) => ` + +${files + .map( + ([file, tests, failures, skipped]) => + ` + + + `, + ) + .join("\n")} +`; + +describe("parseJunit", () => { + it("counts each file's top-level suite only", () => { + const parsed = parseJunit( + report([ + ["tests/unit/a.test.ts", 5, 1, 1], + ["tests/unit/b.test.ts", 2, 0, 0], + ]), + ); + expect(parsed.seconds).toBe(1.5); + expect(parsed.files.get("tests/unit/a.test.ts")).toEqual({ + passed: 3, + failed: 1, + skipped: 1, + }); + expect(parsed.files.get("tests/unit/b.test.ts")).toEqual({ + passed: 2, + failed: 0, + skipped: 0, + }); + expect(parsed.files.size).toBe(2); + }); +}); + +describe("compareReports", () => { + const serial = parseJunit( + report([ + ["tests/unit/a.test.ts", 5, 0, 0], + ["tests/unit/b.test.ts", 2, 0, 0], + ]), + ); + + it("finds nothing when every file matches", () => { + const parallel = parseJunit( + report([ + ["tests/unit/b.test.ts", 2, 0, 0], + ["tests/unit/a.test.ts", 5, 0, 0], + ]), + ); + expect(compareReports(serial, parallel)).toEqual([]); + }); + + it("reports a file whose counts differ", () => { + const parallel = parseJunit( + report([ + ["tests/unit/a.test.ts", 5, 1, 0], + ["tests/unit/b.test.ts", 2, 0, 0], + ]), + ); + expect(compareReports(serial, parallel)).toEqual([ + "tests/unit/a.test.ts: serial 5 passed, 0 failed, 0 skipped; parallel 4 passed, 1 failed, 0 skipped", + ]); + }); + + it("reports a file only one run has", () => { + const parallel = parseJunit(report([["tests/unit/a.test.ts", 5, 0, 0]])); + expect(compareReports(serial, parallel)).toEqual([ + "tests/unit/b.test.ts: serial 2 passed, 0 failed, 0 skipped; parallel missing", + ]); + }); +}); + +describe("mergeReports", () => { + it("joins runs over different files into one report", () => { + const merged = mergeReports([ + parseJunit(report([["tests/unit/a.test.ts", 5, 0, 0]], 2)), + parseJunit(report([["tests/unit/b.test.ts", 2, 1, 0]], 3)), + ]); + expect(merged.seconds).toBe(5); + expect([...merged.files.keys()].sort()).toEqual([ + "tests/unit/a.test.ts", + "tests/unit/b.test.ts", + ]); + expect(merged.files.get("tests/unit/b.test.ts")?.failed).toBe(1); + }); +}); diff --git a/tests/unit/ci/e2e-shards.test.ts b/tests/unit/ci/e2e-shards.test.ts index 1a8e1109..0ced0a1e 100644 --- a/tests/unit/ci/e2e-shards.test.ts +++ b/tests/unit/ci/e2e-shards.test.ts @@ -3,6 +3,8 @@ import { describe, expect, it } from "bun:test"; import { packShards, parseTimings, + smoothTimings, + type Timings, timingsFromReport, } from "../../../scripts/e2e-shards"; @@ -138,3 +140,45 @@ describe("timingsFromReport", () => { }); }); }); + +describe("smoothTimings", () => { + const cases: { + name: string; + current: Timings; + previous: Timings; + expected: Timings; + }[] = [ + { + name: "averages a file timed in both runs", + current: { a: 263 }, + previous: { a: 116 }, + expected: { a: 189.5 }, + }, + { + name: "keeps a new file's own time", + current: { a: 10, fresh: 42 }, + previous: { a: 20 }, + expected: { a: 15, fresh: 42 }, + }, + { + name: "drops a file the new run did not time", + current: { a: 10 }, + previous: { a: 10, deleted: 300 }, + expected: { a: 10 }, + }, + { + name: "converges on a steady time", + current: { a: 100 }, + previous: { a: 100 }, + expected: { a: 100 }, + }, + ]; + + it.each(cases)("$name", ({ current, previous, expected }) => { + expect(smoothTimings(current, previous)).toEqual(expected); + }); + + it("weights the newest run as asked", () => { + expect(smoothTimings({ a: 100 }, { a: 0 }, 0.25)).toEqual({ a: 25 }); + }); +}); diff --git a/tests/unit/ci/unit-tests.test.ts b/tests/unit/ci/unit-tests.test.ts new file mode 100644 index 00000000..c63ea453 --- /dev/null +++ b/tests/unit/ci/unit-tests.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "bun:test"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { plan, SERIAL_FILES, STRESS } from "../../../scripts/unit-tests"; + +const ROOT = process.cwd(); + +const testFiles = (dir: string): string[] => + readdirSync(path.join(ROOT, dir), { withFileTypes: true }).flatMap( + (entry) => { + const relative = `${dir}/${entry.name}`; + if (entry.isDirectory()) return testFiles(relative); + return /\.test\.tsx?$/.test(entry.name) ? [relative] : []; + }, + ); + +// Reads a clock and asserts an upper bound: a wall-clock budget, which +// --parallel can blow by sharing the CPU with other files. +const CLOCK = /performance\.now\(\)|Date\.now\(\)|Bun\.nanoseconds\(\)/; +const BUDGET = /toBeLessThan(OrEqual)?\(/; + +describe("scripts/unit-tests.ts", () => { + it("lists files that exist", () => { + for (const file of SERIAL_FILES) { + expect(existsSync(path.join(ROOT, file)), file).toBe(true); + } + }); + + it("runs every unit test with a wall-clock budget serially", () => { + const timed = testFiles("tests/unit") + .filter((file) => !file.startsWith("tests/unit/stress/")) + .filter((file) => { + const source = readFileSync(path.join(ROOT, file), "utf8"); + return CLOCK.test(source) && BUDGET.test(source); + }); + expect(timed.sort()).toEqual([...SERIAL_FILES].sort()); + }); + + it("runs the rest in parallel, then the timed files serially", () => { + const [parallel, serial] = plan(false); + expect(parallel).toContain("--parallel"); + expect(parallel).toContain(`--path-ignore-patterns=${STRESS}`); + for (const file of SERIAL_FILES) { + expect(parallel).toContain(`--path-ignore-patterns=${file}`); + expect(serial).toContain(file); + } + expect(serial).not.toContain("--parallel"); + }); + + it("runs everything serially with UNIT_SERIAL", () => { + const runs = plan(true); + expect(runs).toHaveLength(1); + expect(runs[0]).not.toContain("--parallel"); + expect(runs[0]).toContain(`--path-ignore-patterns=${STRESS}`); + }); + + it("writes JUnit reports when asked", () => { + const [parallel, serial] = plan(false, "/tmp/x"); + expect(parallel).toContain("--reporter-outfile=/tmp/x/parallel.xml"); + expect(serial).toContain("--reporter-outfile=/tmp/x/serial.xml"); + expect(plan(true, "/tmp/x")[0]).toContain( + "--reporter-outfile=/tmp/x/all.xml", + ); + }); +}); diff --git a/tests/unit/desktop/storage/derive-crash-loss.test.ts b/tests/unit/desktop/storage/derive-crash-loss.test.ts new file mode 100644 index 00000000..fcf9b84b --- /dev/null +++ b/tests/unit/desktop/storage/derive-crash-loss.test.ts @@ -0,0 +1,164 @@ +/** + * The condition on D-A6's amendment (derived rows commit at + * `synchronous=NORMAL`): a power cut may lose the last derive commit while + * the content append before it, committed FULL, survives. The derived rows + * and `derived_seq` are lost together, so the document reads as stale and + * the next derive puts them back. + * + * A power cut is simulated on the files. Right after the FULL append the + * main file and the WAL are what a synced disk holds; the derive then adds + * frames that were never synced. After a crash the main file is put back + * and the WAL is cut to the append's end (the derive's commit dropped) or + * into the derive's first frame (a torn tail). Closing the connection would + * checkpoint the WAL into the main file, hence the copy taken before it. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { + existsSync, + readFileSync, + rmSync, + statSync, + truncateSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; + +import * as Y from "yjs"; + +import type { DerivedRows } from "@/desktop/storage/engine/derive"; +import { LIBRARY_FILE, type Library } from "@/desktop/storage/engine/library"; +import { + crash, + createClock, + createTempDir, + createTestHost, + openTestLibrary, +} from "@/tests/helpers/storage-library"; + +const TARGET = "ab".repeat(16); + +let temp: ReturnType; +const open: Library[] = []; + +beforeEach(() => { + temp = createTempDir(); +}); +afterEach(() => { + for (const library of open.splice(0)) library.shutdown(); + temp.cleanUp(); +}); + +function openLibrary(): Library { + const library = openTestLibrary(temp.dir, createTestHost(createClock())); + open.push(library); + return library; +} + +const rows: DerivedRows = { + links: [ + { + ord: 0, + src_toc_id: "", + target_key: TARGET, + target_toc_id: "", + text: "see", + context: "see the other one", + }, + ], + headings: [{ ord: 0, toc_id: "h1", level: 1, text: "Intro" }], + title: "Linked", + snippet: "snippet", +}; + +function textOf(library: Library, id: string): string { + const content = library.load(id, "check"); + const doc = new Y.Doc(); + if (content.snapshot) Y.applyUpdate(doc, content.snapshot); + for (const update of content.updates) Y.applyUpdate(doc, update); + library.close(id, "check"); + return doc.getText("t").toString(); +} + +/** + * One document with a FULL append and a NORMAL derive after it. Returns the + * files as they stood after the append, and the WAL's length then. + */ +function appendThenDerive() { + const path = join(temp.dir, LIBRARY_FILE); + const library = openLibrary(); + const { id } = library.createDoc({ title: "Linked" }); + library.load(id, "w"); + const doc = new Y.Doc(); + doc.getText("t").insert(0, "kept"); + const seq = library.append(id, "w", { + origin: "local", + update: Y.encodeStateAsUpdate(doc), + }); + library.close(id, "w"); + // What a synced disk holds now: the FULL append is in the WAL. + const main = readFileSync(path); + const walEnd = statSync(`${path}-wal`).size; + expect(walEnd).toBeGreaterThan(0); + expect(library.putDerived(id, seq, rows)).toBe("ok"); + expect(library.backlinks(TARGET)).toHaveLength(1); + const wal = readFileSync(`${path}-wal`); + expect(wal.byteLength).toBeGreaterThan(walEnd); + crash(library); + open.splice(open.indexOf(library), 1); + return { id, seq, path, main, wal, walEnd }; +} + +/** Puts the "synced" files back, the WAL cut at `walLength`. */ +function powerCut( + files: ReturnType, + walLength: number, +) { + writeFileSync(files.path, files.main); + writeFileSync(`${files.path}-wal`, files.wal); + truncateSync(`${files.path}-wal`, walLength); + // A cold start: the WAL index is rebuilt from the WAL itself. + if (existsSync(`${files.path}-shm`)) rmSync(`${files.path}-shm`); +} + +describe("a power cut after a NORMAL derive commit (D-A6 amendment)", () => { + const cuts: [ + string, + (files: ReturnType) => number, + ][] = [ + ["the derive's commit is dropped", (files) => files.walEnd], + // 32-byte WAL header, then frames of a 24-byte header and one page. + [ + "the WAL tail is torn inside the derive's first frame", + (files) => files.walEnd + 24 + 100, + ], + ]; + + for (const [name, cutAt] of cuts) + test(name, () => { + const files = appendThenDerive(); + powerCut(files, cutAt(files)); + + const library = openLibrary(); + expect(library.status.uncleanExit).toBe(true); + expect(library.status.quickCheck).toBe("ok"); + expect(library.status.readOnly).toBeNull(); + // The FULL append survived; the derive did not. + expect(textOf(library, files.id)).toBe("kept"); + expect(library.backlinks(TARGET)).toEqual([]); + // derived_seq went with its rows: the document reads as stale. + expect(library.nextStale()).toBe(files.id); + + // The derive queue puts the rows back. + expect(library.putDerived(files.id, files.seq, rows)).toBe("ok"); + expect(library.backlinks(TARGET)).toHaveLength(1); + expect(library.nextStale()).toBeNull(); + }); + + test("control: with the WAL whole, the derive survives the crash", () => { + const files = appendThenDerive(); + powerCut(files, files.wal.byteLength); + const library = openLibrary(); + expect(library.backlinks(TARGET)).toHaveLength(1); + expect(library.nextStale()).toBeNull(); + }); +}); diff --git a/tests/unit/scripts/nightly-streak.test.ts b/tests/unit/scripts/nightly-streak.test.ts index ad6ea169..229d4428 100644 --- a/tests/unit/scripts/nightly-streak.test.ts +++ b/tests/unit/scripts/nightly-streak.test.ts @@ -605,6 +605,11 @@ const TEST_STEPS = [ "Smoke", "Soak", "Property test", + // CI's parallel unit tests checked against a serial run (unit-runs). + "Unit tests (serial)", + "Unit tests (as CI runs them)", + "Compare serial and parallel", + "Stress benchmark (informational)", // The desktop shell (#135): building, installing and checking the app. "Export the desktop renderer", "Audit the packaging dependencies",