From 0d3fbaa6a9910f837ef38e467823e7cb89f48ccd Mon Sep 17 00:00:00 2001 From: IvGolovach <20299097+IvGolovach@users.noreply.github.com> Date: Mon, 25 May 2026 14:09:39 -0700 Subject: [PATCH] test(frontend): add CI coverage for tests and migrations Validation * Validation tier: Tier 4 - CI/test tooling, because this adds a focused frontend CI workflow plus migration replay verification without changing runtime behavior. * bun install --frozen-lockfile: PASS * bun run --cwd packages/frontend test: PASS, 29 files and 251 tests passed. * DATABASE_URL=postgres://postgres:postgres@localhost:/tokscale_ci NODE_ENV=test bun run --cwd packages/frontend test:migrations: PASS against postgres:16, migrations applied and schema smoke checks passed. * ruby -e 'require "yaml"; YAML.load_file(".github/workflows/frontend_ci.yml"); puts "yaml ok"': PASS * perl -ne 'print if /[\x{0400}-\x{04FF}]/' .github/workflows/frontend_ci.yml packages/frontend/package.json packages/frontend/scripts/check-migrations.ts: PASS, no output. * git diff --check: PASS * git diff --cached --check: PASS * Ledger: not applicable - not required for selected validation tier/change family. * Version: not applicable - not required for selected validation tier/change family. * Non-gating observation: bun run --cwd packages/frontend lint currently fails on pre-existing unrelated app lint errors outside this diff; the new workflow does not introduce lint as a frontend gate. * Not run: actionlint - not installed locally. Rollback * git revert HEAD --- .github/workflows/frontend_ci.yml | 78 ++++++ packages/frontend/package.json | 2 + packages/frontend/scripts/check-migrations.ts | 226 ++++++++++++++++++ 3 files changed, 306 insertions(+) create mode 100644 .github/workflows/frontend_ci.yml create mode 100644 packages/frontend/scripts/check-migrations.ts diff --git a/.github/workflows/frontend_ci.yml b/.github/workflows/frontend_ci.yml new file mode 100644 index 000000000..3783ec227 --- /dev/null +++ b/.github/workflows/frontend_ci.yml @@ -0,0 +1,78 @@ +name: Frontend CI + +on: + workflow_dispatch: + push: + branches: [main, develop] + paths: + - "packages/frontend/**" + - "package.json" + - "bun.lock" + - ".github/workflows/frontend_ci.yml" + pull_request: + branches: [main, develop] + paths: + - "packages/frontend/**" + - "package.json" + - "bun.lock" + - ".github/workflows/frontend_ci.yml" + +permissions: + contents: read + +env: + BUN_VERSION: 1.3.10 + +jobs: + vitest: + name: Frontend Vitest + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Set up Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: ${{ env.BUN_VERSION }} + + - name: Install workspace dependencies + run: bun install --frozen-lockfile + + - name: Run frontend tests + run: bun run --cwd packages/frontend test + + migration-replay: + name: Frontend Migration Replay + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: tokscale_ci + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d tokscale_ci" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + env: + DATABASE_URL: postgres://postgres:postgres@localhost:5432/tokscale_ci + NODE_ENV: test + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Set up Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: ${{ env.BUN_VERSION }} + + - name: Install workspace dependencies + run: bun install --frozen-lockfile + + - name: Replay frontend database migrations + run: bun run --cwd packages/frontend test:migrations diff --git a/packages/frontend/package.json b/packages/frontend/package.json index 8adb716a3..6c5b5b67c 100644 --- a/packages/frontend/package.json +++ b/packages/frontend/package.json @@ -7,6 +7,8 @@ "build": "next build", "start": "next start", "lint": "eslint", + "test": "vitest run", + "test:migrations": "drizzle-kit migrate && bun scripts/check-migrations.ts", "gallery": "bun scripts/gallery/build-gallery.ts", "db:generate": "drizzle-kit generate", "db:migrate": "drizzle-kit migrate", diff --git a/packages/frontend/scripts/check-migrations.ts b/packages/frontend/scripts/check-migrations.ts new file mode 100644 index 000000000..24c085f9f --- /dev/null +++ b/packages/frontend/scripts/check-migrations.ts @@ -0,0 +1,226 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import postgres from "postgres"; + +const databaseUrl = process.env.DATABASE_URL; + +if (!databaseUrl) { + throw new Error("DATABASE_URL is required"); +} + +const sql = postgres(databaseUrl, { max: 1 }); + +function expect(name: string, condition: boolean, detail?: string) { + if (!condition) { + throw new Error(`${name} failed${detail ? `: ${detail}` : ""}`); + } + + console.log(`ok - ${name}`); +} + +const journalPath = resolve( + import.meta.dir, + "../src/lib/db/migrations/meta/_journal.json" +); +const migrationJournal = JSON.parse(readFileSync(journalPath, "utf8")) as { + entries: unknown[]; +}; + +try { + const [{ count: appliedMigrationCount }] = await sql< + { count: number }[] + >`SELECT count(*)::int AS count FROM "drizzle"."__drizzle_migrations"`; + + expect( + "all migration journal entries were applied", + appliedMigrationCount === migrationJournal.entries.length, + `expected ${migrationJournal.entries.length}, got ${appliedMigrationCount}` + ); + + const requiredTables = await sql<{ table_name: string }[]>` + SELECT table_name + FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name IN ( + 'api_tokens', + 'daily_breakdown', + 'device_codes', + 'group_invites', + 'group_members', + 'groups', + 'sessions', + 'submissions', + 'submitted_devices', + 'users' + ) + `; + const tableNames = new Set(requiredTables.map((row) => row.table_name)); + const missingTables = [ + "api_tokens", + "daily_breakdown", + "device_codes", + "group_invites", + "group_members", + "groups", + "sessions", + "submissions", + "submitted_devices", + "users", + ].filter((tableName) => !tableNames.has(tableName)); + + expect( + "required public tables exist", + missingTables.length === 0, + missingTables.join(", ") + ); + + const columnRows = await sql< + { + table_name: string; + column_name: string; + is_nullable: string; + column_default: string | null; + }[] + >` + SELECT table_name, column_name, is_nullable, column_default + FROM information_schema.columns + WHERE table_schema = 'public' + AND ( + (table_name = 'submissions' AND column_name IN ('reasoning_tokens', 'schema_version', 'submit_count')) + OR (table_name = 'daily_breakdown' AND column_name IN ('submitted_device_id', 'active_time_ms')) + ) + `; + const columns = new Map( + columnRows.map((row) => [`${row.table_name}.${row.column_name}`, row]) + ); + + expect( + "submit_count is present with a default", + columns.get("submissions.submit_count")?.column_default === "1" + ); + expect( + "submitted_device_id is required", + columns.get("daily_breakdown.submitted_device_id")?.is_nullable === "NO" + ); + expect( + "time and schema columns are present", + [ + "submissions.reasoning_tokens", + "submissions.schema_version", + "daily_breakdown.active_time_ms", + ].every((columnName) => columns.has(columnName)) + ); + + const removedColumns = await sql<{ count: number }[]>` + SELECT count(*)::int AS count + FROM information_schema.columns + WHERE table_schema = 'public' + AND ( + (table_name = 'users' AND column_name = 'is_admin') + OR (table_name = 'submissions' AND column_name = 'status') + OR (table_name = 'daily_breakdown' AND column_name IN ('provider_breakdown', 'model_breakdown')) + ) + `; + + expect("removed columns stay removed", removedColumns[0].count === 0); + + const indexRows = await sql<{ indexname: string; indexdef: string }[]>` + SELECT indexname, indexdef + FROM pg_indexes + WHERE schemaname = 'public' + AND indexname IN ( + 'idx_device_codes_user_id', + 'idx_group_invites_invited_by', + 'idx_group_members_invited_by', + 'idx_submissions_leaderboard', + 'users_username_lower_unique' + ) + `; + const indexes = new Map(indexRows.map((row) => [row.indexname, row.indexdef])); + + expect( + "required indexes exist", + [ + "idx_device_codes_user_id", + "idx_group_invites_invited_by", + "idx_group_members_invited_by", + "idx_submissions_leaderboard", + "users_username_lower_unique", + ].every((indexName) => indexes.has(indexName)) + ); + expect( + "case-insensitive username index is unique", + indexes.get("users_username_lower_unique")?.includes("UNIQUE INDEX") === true && + indexes.get("users_username_lower_unique")?.includes("lower((username)::text)") === + true + ); + + const extensionRows = await sql<{ count: number }[]>` + SELECT count(*)::int AS count + FROM pg_extension + WHERE extname = 'pgcrypto' + `; + + expect("pgcrypto extension is available", extensionRows[0].count === 1); + + await sql`BEGIN`; + try { + const [user] = await sql<{ id: string }[]>` + INSERT INTO "users" ("github_id", "username") + VALUES (1001, 'ci_migration_replay') + RETURNING "id" + `; + const [submission] = await sql<{ id: string }[]>` + INSERT INTO "submissions" ( + "user_id", + "total_tokens", + "total_cost", + "input_tokens", + "output_tokens", + "date_start", + "date_end", + "sources_used", + "models_used" + ) + VALUES ( + ${user.id}, + 42, + 0.4200, + 20, + 22, + '2026-05-25', + '2026-05-25', + ARRAY['codex'], + ARRAY['gpt-5'] + ) + RETURNING "id" + `; + const [device] = await sql<{ id: string }[]>` + INSERT INTO "submitted_devices" ("user_id", "device_key", "display_name") + VALUES (${user.id}, 'ci-device', 'CI device') + RETURNING "id" + `; + await sql` + INSERT INTO "daily_breakdown" ( + "submission_id", + "submitted_device_id", + "date", + "tokens", + "cost", + "input_tokens", + "output_tokens" + ) + VALUES (${submission.id}, ${device.id}, '2026-05-25', 42, 0.4200, 20, 22) + `; + await sql` + INSERT INTO "groups" ("name", "slug", "created_by") + VALUES ('CI Group', 'ci-group', ${user.id}) + `; + } finally { + await sql`ROLLBACK`; + } + + expect("schema accepts representative inserts", true); +} finally { + await sql.end(); +}