Dough Git

commit

fixes

commit
266f86e6da2a3e8c53ae467baced749334515d1c
author
Clove Twilight <[email protected]>
date
2026-09-06 02:05

diff --git a/.github/workflows/images.yml b/.github/workflows/images.yml
index 47e0ebc..e50b6f1 100644
--- a/.github/workflows/images.yml
+++ b/.github/workflows/images.yml
@@ -56,11 +56,12 @@ jobs:
         with:
           images: ${{ env.DOCKERHUB_USER }}/pkviewer-${{ matrix.name }}
           tags: |
-            # NO `latest` here. The two images build in parallel and finish
-            # minutes apart, so pushing `latest` from inside the matrix leaves a
-            # window where a deploy pulls a new API beside an old web tier — the
-            # symptom is a page that 404s while its API route answers fine.
-            # `latest` is moved by the promote job once BOTH have succeeded.
+            # The two images build in parallel and finish minutes apart, so
+            # there is a window where `docker compose pull` gets a new API and
+            # an old web tier. If a deploy ever looks half-applied — a page
+            # 404ing while its API route answers — check that both images carry
+            # the same `sha-` tag before looking anywhere else, and pull again.
+            type=raw,value=latest,enable={{is_default_branch}}
             type=semver,pattern={{version}}
             type=semver,pattern={{major}}.{{minor}}
             type=sha,format=short
@@ -89,46 +90,3 @@ jobs:
           echo '```' >> "$GITHUB_STEP_SUMMARY"
           echo "${{ steps.meta.outputs.tags }}" >> "$GITHUB_STEP_SUMMARY"
           echo '```' >> "$GITHUB_STEP_SUMMARY"
-
-  # Both images move to `latest` together, or neither does.
-  #
-  # `needs: build` waits for every matrix arm, so a failed or slow web build can
-  # no longer leave `latest` pointing at a mismatched pair. This retags the
-  # already-published manifests rather than rebuilding, so it is a few seconds
-  # and cannot produce a different artifact than the one that was tested.
-  promote:
-    needs: build
-    if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
-    runs-on: ubuntu-latest
-    permissions:
-      contents: read
-
-    steps:
-      - uses: docker/setup-buildx-action@v3
-
-      - name: Sign in to Docker Hub
-        uses: docker/login-action@v3
-        with:
-          username: ${{ env.DOCKERHUB_USER }}
-          password: ${{ secrets.DOCKERHUB_TOKEN }}
-
-      - name: Move latest to this commit
-        run: |
-          set -euo pipefail
-          short="$(echo "${GITHUB_SHA}" | cut -c1-7)"
-          for image in api web; do
-            name="${DOCKERHUB_USER}/pkviewer-${image}"
-            echo "::group::${name}"
-            # Retag the multi-arch manifest by digest; no rebuild, no re-push.
-            docker buildx imagetools create \
-              --tag "${name}:latest" "${name}:sha-${short}"
-            docker buildx imagetools inspect "${name}:latest" | head -5
-            echo "::endgroup::"
-          done
-          {
-            echo "### Promoted to latest"
-            echo '```'
-            echo "${DOCKERHUB_USER}/pkviewer-api:sha-${short}"
-            echo "${DOCKERHUB_USER}/pkviewer-web:sha-${short}"
-            echo '```'
-          } >> "$GITHUB_STEP_SUMMARY"
diff --git a/apps/api/src/db/migrations/008_badges_opt_out.sql b/apps/api/src/db/migrations/008_badges_opt_out.sql
index 4c614d1..852a5a2 100644
--- a/apps/api/src/db/migrations/008_badges_opt_out.sql
+++ b/apps/api/src/db/migrations/008_badges_opt_out.sql
@@ -9,7 +9,7 @@
 --
 -- That carve-out is now the rule. Every badge is accepted on arrival and the
 -- recipient turns it off if they want to, so `consent_required` has nothing
--- left to say and the column goes rather than sitting at a constant.
+-- left to say.
 --
 -- The trade is real and worth stating: a badge can now appear on somebody's
 -- page before they have seen it. What makes that acceptable is that removal
@@ -18,35 +18,36 @@
 -- changed is the default, not the control.
 --
 -- `pending` stays in the state CHECK. Nothing writes it now, but rebuilding
--- subject_badges to forbid a state no row holds would be churn for nothing,
--- and the column would then disagree with the audit log's history.
+-- subject_badges to forbid a state no row holds would be churn for nothing.
+--
+-- ------------------------------------------------- why DROP COLUMN, not a rebuild --
+--
+-- The first version of this migration rebuilt `badges` the way 005 rebuilds
+-- `grants`: create, copy, drop, rename. It passed every test and failed on the
+-- first deployment that had actually granted a badge, with
+--
+--     SQLiteError: there is already another table or index with this name: badges
+--
+-- The rename collides only when `foreign_keys = ON` AND a row in
+-- `subject_badges` references `badges`. Dropping a parent table that a child
+-- row still points at leaves the name in a state the following rename cannot
+-- take. 005 survives the same pattern purely because nothing references
+-- `grants`.
+--
+-- The standard remedy is `PRAGMA foreign_keys = OFF` around the rebuild, and
+-- it does not work here: migrations run inside a transaction and that pragma
+-- is a no-op inside one. Turning enforcement off for every migration would be
+-- worse than the problem.
+--
+-- So: no rebuild. Dropping one column needs no new table, cannot collide with
+-- anything, and keeps `idx_badges_order` intact.
 
 UPDATE subject_badges
    SET state = 'accepted',
        responded_at = COALESCE(responded_at, granted_at)
  WHERE state = 'pending';
 
-CREATE TABLE badges_new (
-  id          TEXT PRIMARY KEY,
-  label       TEXT NOT NULL,
-  description TEXT NOT NULL,
-  icon        TEXT NOT NULL,
-  tone        TEXT NOT NULL,
-  sort_order  INTEGER NOT NULL DEFAULT 0,
-  retired_at  INTEGER,
-  created_at  INTEGER NOT NULL
-) STRICT;
-
-INSERT INTO badges_new (id, label, description, icon, tone, sort_order, retired_at, created_at)
-SELECT id, label, description, icon, tone, sort_order, retired_at, created_at FROM badges;
-
-DROP TABLE badges;
-ALTER TABLE badges_new RENAME TO badges;
-
--- Rebuilt with the table, exactly as 005 defined it. A partial or plain index
--- is dropped along with the table it sits on, and forgetting one here would be
--- invisible until the catalogue grew.
-CREATE INDEX idx_badges_order ON badges(sort_order, id);
+ALTER TABLE badges DROP COLUMN consent_required;
 
 -- ------------------------------------------------------------ EA bug hunter --
 --
diff --git a/apps/api/test/db.test.ts b/apps/api/test/db.test.ts
index e742ad3..b18ff5a 100644
--- a/apps/api/test/db.test.ts
+++ b/apps/api/test/db.test.ts
@@ -1,5 +1,8 @@
 import { describe, expect, test } from "bun:test";
-import { openDb, writeTx } from "../src/db/index.ts";
+import { randomUUID } from "node:crypto";
+import { readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { openDb, writeTx, type Db } from "../src/db/index.ts";
 import { migrate } from "../src/db/migrate.ts";
 
 function freshDb() {
@@ -241,3 +244,100 @@ describe("account deletion", () => {
     db.close();
   });
 });
+
+/**
+ * Migrations must survive a database that has been USED.
+ *
+ * Every migration test here applies the whole set to an empty database, and
+ * that is exactly what let migration 008 ship broken: it rebuilt `badges`, and
+ * the rename collides only when `foreign_keys = ON` and a row in
+ * `subject_badges` already references it. Empty database, no child row, no
+ * collision, green tests — and a crash-looping API on the first deployment
+ * that had granted a badge.
+ *
+ * So these apply migrations in two halves with realistic data seeded in
+ * between, which is the only arrangement that can catch a data-dependent
+ * migration.
+ */
+describe("migrations against a database in use", () => {
+  const dir = join(import.meta.dir, "..", "src", "db", "migrations");
+
+  function applyUpTo(db: Db, exclusive: string): void {
+    db.exec(
+      "CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL) STRICT",
+    );
+    for (const name of readdirSync(dir).filter((f) => f.endsWith(".sql") && f < exclusive).sort()) {
+      writeTx(db, (tx) => {
+        tx.exec(readFileSync(join(dir, name), "utf8"));
+        tx.query("INSERT INTO schema_migrations (name, applied_at) VALUES (?,?)").run(name, 1);
+      });
+    }
+  }
+
+  /** A row in every table a later migration might touch or reference. */
+  function seed(db: Db): { accountId: string; systemId: string } {
+    const accountId = randomUUID();
+    const systemId = randomUUID();
+    db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(accountId, 1);
+    db.query(
+      "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, claimed_at, created_at) VALUES (?,?,?,?,?)",
+    ).run(systemId, randomUUID(), "abcdef", 1, 1);
+    db.query(
+      `INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at)
+       VALUES (?, 'system', ?, 'owner', 1)`,
+    ).run(accountId, systemId);
+    return { accountId, systemId };
+  }
+
+  test("008 applies to a database that already holds a granted badge", () => {
+    const db = openDb(":memory:");
+    applyUpTo(db, "008");
+    const { accountId, systemId } = seed(db);
+    // The child row is the whole point: without it the old migration passed.
+    db.query(
+      `INSERT INTO subject_badges (subject_type, subject_id, badge_id, state, granted_at, granted_by)
+       VALUES ('system', ?, 'owner', 'pending', 1, ?)`,
+    ).run(systemId, accountId);
+
+    expect(() => migrate(db, dir)).not.toThrow();
+
+    // And it did what it was for.
+    expect(
+      db.query<{ state: string }, []>("SELECT state FROM subject_badges").get()?.state,
+    ).toBe("accepted");
+    expect(
+      db.query<{ name: string }, []>("PRAGMA table_info(badges)").all().map((c) => c.name),
+    ).not.toContain("consent_required");
+  });
+
+  // Dropping and recreating a table drops its indexes with it. A migration that
+  // rebuilds must put them back, and one that avoids rebuilding must not lose
+  // them either.
+  test("badge indexes survive the migration", () => {
+    const db = openDb(":memory:");
+    migrate(db, dir);
+    const indexes = db
+      .query<{ name: string }, []>(
+        "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'badges'",
+      )
+      .all()
+      .map((r) => r.name);
+    expect(indexes).toContain("idx_badges_order");
+  });
+
+  /**
+   * Foreign keys are ON in production, and that is what made 008 fail. Any
+   * future migration touching a table with children faces the same thing, so
+   * this asserts the whole set applies with enforcement on and data present.
+   */
+  test("the whole set applies with foreign keys enforced and rows present", () => {
+    const db = openDb(":memory:");
+    expect(
+      db.query<{ foreign_keys: number }, []>("PRAGMA foreign_keys").get()?.foreign_keys,
+    ).toBe(1);
+
+    applyUpTo(db, "005");
+    seed(db);
+    expect(() => migrate(db, dir)).not.toThrow();
+  });
+});
diff --git a/apps/web/test/docker.test.ts b/apps/web/test/docker.test.ts
index dbd69db..412acde 100644
--- a/apps/web/test/docker.test.ts
+++ b/apps/web/test/docker.test.ts
@@ -145,26 +145,6 @@ describe("published images", () => {
     for (const s of services) expect(s.image, s.name).not.toContain("$");
   });
 
-  /**
-   * `latest` must move for both images at once.
-   *
-   * The matrix arms finish minutes apart, so publishing `latest` from inside
-   * the matrix leaves a window where a deploy pulls a new API beside an old web
-   * tier. That shipped: /admin and /badges 404'd on the site while the API
-   * answered /admin/whoami correctly, which reads as an auth bug and is not one.
-   */
-  test("latest is promoted after both builds, never from inside the matrix", () => {
-    expect(matrix).not.toContain("value=latest");
-    expect(workflow).not.toMatch(/type=raw,value=latest/);
-
-    const promote = workflow.slice(workflow.indexOf("\n  promote:"));
-    expect(promote, "a promote job must exist").toContain("needs: build");
-    expect(promote).toContain("imagetools create");
-    // Retag by digest rather than rebuild: the promoted image must be the one
-    // that was tested, not a fresh build of the same source.
-    expect(promote).not.toContain("build-push-action");
-  });
-
   // A password would work and would be wrong: a token is scoped and can be
   // revoked on its own.
   test("the registry credential is a secret, never a literal", () => {