Skip to content

Conversation

erikhfj
Copy link
Member

@erikhfj erikhfj commented Nov 24, 2026 •

Closes #134

What was done

CI/CD & lint hardening

  • Zero-warning lint gate: Updated root package.json "lint" to eslint . --max-warnings 0 (matches AGENTS.md).
  • Playwright E2E CI job: Added e2e job to .github/workflows/ci.yml running on PRs and pushes to main (gating deploy alongside quality and integration):
    • Starts a throwaway unix-socket-only PostgreSQL cluster, applies migrations, and seeds with db:seed.
    • Builds server and client, starts the API on an ephemeral localhost port (so it never collides with live crate-api.service on port 3001) and vite preview proxying /graphql via VITE_API_PROXY_TARGET.
    • Uses a single shared ~/.cache/ms-playwright install with playwright install chromium --only-shell, prunes older chromium_headless_shell-* builds so Playwright upgrades do not fill the VM's disk, prints the last 50 lines of e2e-api.log and e2e-client.log on failure (if: failure()), and removes temp DBs/logs/test-results/playwright-report in if: always().
  • Least-privilege token, pinned actions, & safe concurrency:
    • Added top-level permissions: { contents: read } and pinned actions/checkout, pnpm/action-setup, and actions/setup-node to full v4.3.0/v4.4.0 commit SHAs with version comments.
    • Note on self-hosted runner trust boundary: contents: read limits GITHUB_TOKEN on GitHub only. Because PR jobs currently run on it2810-19 under the same OS user that deploys (with access to ~/T19-Project-2/.env, /var/www/html/project2, and sudo systemctl restart crate-api), only trusted group members should open PRs; moving PR checks to a separate unprivileged runner user would isolate this further.
    • Set cancel-in-progress: ${{ github.event_name == 'pull_request' }} so superseded PR runs cancel, while pushes to main never cancel an in-progress deploy halfway.
  • API-first deploy, staged frontend swap with backup, & hardened rollback:
    • Installs the EXIT trap and initializes state flags (API_TOUCHED, MIGRATIONS_CHANGED, MIGRATIONS_APPLIED, FRONTEND_SWAPPED, DEPLOY_OK) at the very top of the deploy step before the first prerequisite check so early failures never leave .new/.prev behind.
    • Deploys, migrates, imports, restarts, and smoke-tests the API first, then publishes the Apache frontend last via a staged directory swap with backup (.new/.prev sibling directories with a RUNNER_TEMP copy fallback if /var/www/html is not writable — not strictly atomic since two mvs leave a brief window).
    • Database is NOT rolled back: server/drizzle/*.sql migrations and the in-place MusicBrainz import are forward-only (expand first, contract in a later PR). If server/drizzle/ changed between PREV_SHA and GITHUB_SHA and migrations were already applied before a failure, automatic API code rollback is skipped with a loud ::error:: annotation for manual intervention (while still rolling back the frontend if swapped).
    • Emits ::error::Rollback failed, crate-api may be down if rebuilding, restarting, or waiting for /graphql fails during API rollback.

Real PostgreSQL integration tests

  • Added server/src/reviews.postgres.test.ts covering saveReview (upsertReview), removeReview (deleteReview), cross-user delete protection, DB review_refresh_album_average_rating & review_set_updated_at triggers, reviewsForAlbum keyset cursor pagination across timestamp ties, bad cursor rejection, and GraphQL Yoga execution.
  • Expanded server/src/crate.postgres.test.ts with idempotent addToCrate/removeFromCrate mutation tests, DataLoader priming, missing-album rejection, and cross-user isolation.
  • Registered src/reviews.postgres.test.ts in server/scripts/assert-postgres-tests.mjs and added local pnpm test:integration (server/scripts/run-postgres-tests.mjs).

Expanded Playwright E2E & jsdom accessibility tests

  • Added e2e/tests/crate.spec.ts (add to crate -> /crate -> reload -> remove -> reload) and expanded e2e/tests/search.spec.ts (search history keyboard selection, Load more pagination against 24 seeded albums in server/src/db/seed.ts, review validation & editing, shared multi-filter URL restoration).
  • Added e2e/tests/cleanup.ts to clear fixed E2E users' leftover reviews, crate items, and search history deterministically via GraphQL before running, avoiding UI cleanup races against a reused database.
  • Expanded e2e/tests/a11y.spec.ts with real-browser axe-core WCAG 2.1 A/AA scans for /crate (empty & populated), dark mode (colorScheme: 'dark'), mobile viewport (390x844), open search-history combobox, and ReviewForm validation error state.
  • Added optional webServer configuration in e2e/playwright.config.ts when E2E_BASE_URL is unset, refusing to start/reuse local webServer on it2810-19 without E2E_BASE_URL so live crate-api on port 3001 is never touched.
  • Expanded client/src/a11y.test.tsx (AlbumDetailPage, CratePage populated & empty, open RecentSearches combobox with active option, ReviewForm validation & mutation error states) and cleared localStorage/sessionStorage around each test in client/src/test/setup.ts.

Coordination note: Left docs/VM-setup.md and docs/AI-USAGE.md untouched to avoid merge conflicts with #133 and #135 (the self-hosted PR runner trust boundary note in docs/VM-setup.md is tracked for #133/#135).

What was tested

  • pnpm format:check && pnpm lint && pnpm typecheck && pnpm test && pnpm build — all passed (0 lint warnings; client/src/generated clean).
  • TEST_DATABASE_URL=... pnpm test:integration against a throwaway local PostgreSQL cluster — 17/17 server test files, 217/217 tests passed; assert-postgres-tests.mjs confirmed all 7 database-backed test files executed.
  • CI=1 E2E_BASE_URL=... pnpm test:e2e against a throwaway migrated + seeded PostgreSQL cluster, built API, and vite preview — 20/20 Playwright tests passed on a fresh DB and 20/20 passed again after injecting leftover reviews and crate items into the reused DB.

Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a big step up. CI is green on 9198784. The E2E job is set up carefully: it uses a socket-only throwaway cluster, picks ephemeral ports with --strictPort, and has an if: always() cleanup. The new tests cover the paths that were missing.

Request changes

  1. The rollback trap is installed too late. In "Deploy the API…", trap on_exit EXIT comes after the crate-api.service, server/ and .git checks and after PREV_SHA=…. If any of those fail, set -e exits before the trap exists. The new frontend from the previous step then stays live against the old API, and project2.prev is left behind. Please move API_TOUCHED=0, DEPLOY_OK=0 and the trap to the top of the step, before the first check. rollback already handles API_TOUCHED=0.

  2. Migrations and the import can't be rolled back. server/drizzle/*.sql only goes forward, and db:import:musicbrainz changes the catalog in place. If the restart or the smoke checks fail after db:migrate, the rollback puts the old code back on the new schema. That works for additive migrations, but not for a rename or a dropped column. Please either:

    • write the rule down: migrations must stay compatible with the previous release (expand first, contract in a later PR), or
    • skip the API rollback and fail loudly when server/drizzle/ changed between PREV_SHA and GITHUB_SHA.

    Please also change "rolls back both frontend and API" in the description to say that the database is not rolled back.

Should fix

  1. Concurrency can cancel a deploy halfway. cancel-in-progress: true also applies to main. A second push while a deploy is running cancels it. The trap does fire on SIGTERM, but the runner kills the job a few seconds later, which is in the middle of pnpm install/build. Suggest cancel-in-progress: ${{ github.event_name == 'pull_request' }}.

  2. A failed rollback looks like a normal failure. rollback runs with set +e, and then exit "${status}" reports only the original error. If the rollback build or wait_for_api fails, the API may be down, and the only sign is a line in the log. Please add ::error::Rollback failed, crate-api may be down when wait_for_api fails inside rollback.

  3. The self-hosted runner trust boundary. contents: read is correct, and deploy still works with it. git fetch in ~/T19-Project-2 uses that clone's own credentials, not GITHUB_TOKEN. But it only limits the token. PR jobs run as the same OS user that deploys, so PR code can read ~/T19-Project-2/.env (the production DATABASE_URL), write to /var/www/html/project2 and run sudo systemctl restart crate-api. The new E2E job also starts servers and a browser on the production VM. I know the docs part is planned for #133/#135. But the wording there right now ("so untrusted code cannot modify the repository or deployment state") is too strong. It should say that PR checks run with the deploy user's access, so only group members should open PRs. Better still, run PR jobs on a second runner under a separate user with no sudo and no access to .env.

Non-blocking

  • Pinned SHAs check out. actions/checkout 08eba0b is v4.3.0, and actions/setup-node 49933ea is v4.4.0, on both github.com and the git.ntnu.no mirror (GHES 3.19.17). The mirror has no checkout v4.4.0, so going down to v4.3.0 in 9198784 was the right fix. pnpm/action-setup isn't mirrored, so it comes from github.com. There, b906aff is v4.3.0, which is also what v4 points to now. The YAML comments are correct, but the description says "full v4.4.0 commit SHAs". Please change it to v4.3.0/v4.4.0.
  • Flaky patterns. These don't matter in CI, where the database is fresh. They do matter when running against a reused database:
    • if (await leftover.isVisible()) in the review test doesn't wait, so it can run before the review loads.
    • The while (count() > 0) cleanup loops in crate.spec.ts and a11y.spec.ts can click the same button twice while the mutation is still running.
    • Waiting for the item count to drop, or deleting leftovers through GraphQL in a beforeEach, would be more robust.
    • retries: 1 in CI will also hide flakes. It's worth checking the log for "flaky" from time to time.
  • Failure output is deleted. Cleanup removes e2e-api.log and test-results (where trace: retain-on-failure writes). After a red Playwright run there's nothing left to look at. Suggest printing tail -50 of the API and client logs before deleting them when the job failed.
  • Disk. One shared ~/.cache/ms-playwright is good. But every Playwright bump downloads a new Chromium and the old one stays. A find ~/.cache/ms-playwright -maxdepth 1 -name 'chromium_headless_shell-*' step that keeps only the newest would fix that.
  • Ports. CI is fine. The local webServer uses port 3001 with reuseExistingServer: !CI. Running pnpm test:e2e on the VM without E2E_BASE_URL would reuse the live crate-api and write test data to the production database. Maybe add a comment, or refuse when HOSTNAME is it2810-19.
  • Order of steps. The frontend is swapped before the API is built, migrated and restarted. That's several minutes of new frontend against the old API. Deploying the API first and swapping the frontend last would make that gap shorter and the rollback simpler. "Atomically" also isn't quite right, since it's two mvs with a short 404 in between.
  • Merge conflict with #140. #140 adds a "Confirm delete" step. The review test here then needs Confirm delete after both Delete review clicks, and search.spec.ts will have a small conflict.

@erikhfj erikhfj force-pushed the chore/134-e2e-ci-and-test-hardening branch from 9198784 to 1e96a5c Compare November 26, 2026 19:32
@erikhfj
Copy link
Member Author

erikhfj commented Nov 26, 2026

Thanks for the thorough review, @evenkkl! Rebased onto main (incorporating #136) and addressed every point in 1e96a5c:

Request changes

  1. Rollback trap & deploy step order (.github/workflows/ci.yml):
    • Combined API deploy, frontend publish, and smoke checks into one deploy step that initializes API_TOUCHED=0, MIGRATIONS_CHANGED=0, MIGRATIONS_APPLIED=0, FRONTEND_SWAPPED=0, DEPLOY_OK=0, and installs trap on_exit EXIT at the very top before the first prerequisite check, cleaning up any .new/.prev directories on failure.
    • Reordered the deploy to update, migrate, import, restart, and smoke-test the API first, and publish the frontend last via a staged directory swap with backup (also updated comments/step names to avoid calling two mvs strictly atomic).
  2. Forward-only DB migrations on rollback (.github/workflows/ci.yml + PR description):
    • Checks git -C "${DEPLOY_ROOT}" diff --name-only "${PREV_SHA}" "${GITHUB_SHA}" -- server/drizzle/ before checkout/migration and sets MIGRATIONS_APPLIED=1 immediately before db:migrate.
    • If server/drizzle/ changed and migrations were already applied before a failure, rollback skips automatic API code rollback and emits ::error::Database migrations changed and were already applied; skipping automatic API code rollback — manual intervention required (while still rolling back the frontend if swapped).
    • Documented the expand-first / contract-later policy in .github/workflows/ci.yml and updated the PR description to state explicitly that the database is not rolled back.

Should fix

  1. Concurrency: Changed cancel-in-progress to ${{ github.event_name == 'pull_request' }} so pushes to main never cancel an active deploy halfway.
  2. Loud rollback failure: Added ::error::Rollback failed, crate-api may be down inside rollback whenever checking out, installing, building, restarting, or waiting on /graphql fails, while still exiting with the original failure status.
  3. Self-hosted runner trust boundary & pinned SHA wording: Clarified in .github/workflows/ci.yml and the PR description that permissions: { contents: read } only limits GITHUB_TOKEN on GitHub while PR jobs share the deploy OS user on it2810-19 (so only trusted group members should open PRs; a separate unprivileged PR runner would isolate further). Updated the PR description from "full v4.4.0" to v4.3.0/v4.4.0.

Non-blocking improvements

  • E2E failure logs: Added an if: failure() step before cleanup in the e2e job that prints tail -n 50 of e2e-api.log and e2e-client.log.
  • Playwright browser cache disk hygiene: Pruned older chromium_headless_shell-* directories in ${PLAYWRIGHT_BROWSERS_PATH} keeping only the newest revision.
  • VM port 3001 guard (e2e/playwright.config.ts): Refuses to start/reuse local webServer on it2810-19 when E2E_BASE_URL is unset so live crate-api and the production DB cannot be hit accidentally.
  • Deterministic E2E cleanup (e2e/tests/cleanup.ts, search.spec.ts, crate.spec.ts, a11y.spec.ts): Replaced if (await leftover.isVisible()) and UI while (count() > 0) click loops with deterministic GraphQL cleanup via Playwright request before tests run (verified locally by running the full 20-test suite twice, injecting leftover reviews and crate items before the second run).
  • feat: #132 a11y/theme/UX polish, #133 hero LCP & Apache headers, and #135 final docs/screenshots #140 coordination: Noted on Confirm delete — once feat: #132 a11y/theme/UX polish, #133 hero LCP & Apache headers, and #135 final docs/screenshots #140 merges, we will align e2e/tests/search.spec.ts with the confirmation step.

evenkkl
evenkkl previously approved these changes Nov 26, 2026
Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, all of it checks out. Approving.

  • Runner note: now says plainly that contents: read only limits the token on GitHub, and that PR jobs run as the deploy user with access to .env, the web root and systemctl restart. Good. Note that #137 isn't merged yet, so the permissions: block isn't on main until it is.
  • NODE_ENV: the "supported since #129 / PR #136" note is correct. #136 is merged, and main has the isProduction check.
  • theme-init.js caching: the FilesMatch regex is right, the quoted heredoc keeps the backslashes, and the expected output now lists it.
  • CSP check: the DevTools / Report-Only note is what I was after.
  • Hero markup: the plain src + mobile source is correct now, and the tests check that srcset/sizes/type are gone.
  • Favicon: it's same-origin, so img-src 'self' covers it, and it removes the /favicon.ico 404.

The mobile crop and the image preload from last time are still open, but both were non-blocking. Fine as follow-ups if Lighthouse shows they matter.

@erikhfj
Copy link
Member Author

erikhfj commented Nov 26, 2026

Rebased chore/134-e2e-ci-and-test-hardening cleanly onto latest main (999fab5, containing #136–#142) at 356e22b for final re-approval (@evenkkl):

Verified locally against the full integrated main tree: codegen, format:check, lint --max-warnings 0, typecheck, build (max JS bundle 395,383 B <= 512,000 B), 250 client tests, 236 server tests across all 7 PostgreSQL-backed suites (assert-postgres-tests.mjs), and 20/20 Playwright E2E + axe-core tests.

@erikhfj erikhfj force-pushed the chore/134-e2e-ci-and-test-hardening branch from 1e96a5c to 356e22b Compare November 26, 2026 21:12
Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 356e22b after the rebase onto main. CI is green, including E2E. The deploy rollback, the migration handling and the E2E cleanup all look good. The rebase conflicts are resolved correctly, including Confirm delete and #140's crate button labels. Approving.

@erikhfj erikhfj merged commit 3c4dc35 into main Nov 26, 2026
4 checks passed
Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Run Playwright E2E in CI, expand E2E/Postgres/a11y tests, and harden CI/CD deploy
2 participants