diff --git a/AGENTS.md b/AGENTS.md index 7718e18..57f76d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,10 @@ history). design, the API and testing are in `docs/dev/`. - **Live at https://labops.onrender.com** (#39): one Render container runs the API, worker and web app; Redis is Render Key Value, PostgreSQL is Neon. - Every boot resets the database and reseeds the `demo` operator and scenario - (`reset-demo.ts`, `seed-demo.ts`, #42). `render.yaml`, `deploy/`, + Each boot runs `prepare-demo.ts` under a database lock: it resets the demo if + it has been idle 10 minutes (so every wake from sleep is fresh, while a + deploy beside a running container keeps it), then migrates and reseeds the + `demo` operator and scenario (#42, refined after a deploy race). `render.yaml`, `deploy/`, `docs/infra/DEPLOYMENT.md`. It is the only deployment: the owner decided it never needs more than Render's 512 MB, so the VM path (#38, #43) was removed. - **Keep docs matching the code.** When code changes, update the doc that @@ -90,7 +92,7 @@ kept non-technical). The git-ignored ``` apps/api/src/ index.ts worker.ts app.ts db.ts entrypoints: start here - seed-operator.ts seed-demo.ts reset-demo.ts one-shot boot commands + seed-operator.ts seed-demo.ts prepare-demo.ts one-shot boot commands platform/ config http auth audit observability secrets jobs events-stream modules/ labs events incidents investigations policies recovery integrations metrics demo @@ -274,9 +276,11 @@ projects. That rule was broken once, and it is not optional. "verified"). Check image build times if in doubt. 7b. **The live image**, whenever an app, `deploy/` or `render.yaml` changed: - `scripts/deploy-image-smoke.sh` builds `deploy/Dockerfile` and boots it - twice under 512 MB against a throwaway database. CI runs the same, and - Render deploys only once every check passes (`checksPass`). + `scripts/deploy-image-smoke.sh` builds `deploy/Dockerfile`, starts two + containers at once on one throwaway database (one must reset, the other + keep), then a third past the idle threshold (it must reset), all under + 512 MB. CI runs the same, and Render deploys only once every check passes + (`checksPass`). 8. **The browser journey** on a fresh stack (the smoke run used the demo, so reset first): @@ -434,7 +438,7 @@ them (#31 to #43; #35 was closed unmerged). Jira: story for Phase N is | — | — | #39 | Free single-container deploy on Render with Neon (`render.yaml`, `deploy/` (then `deploy/render/`), `seed-demo.ts`); live at https://labops.onrender.com | | — | — | #40 | Security headers sent by the web app (`next.config.mjs`) | | — | — | #41 | Plain-language README; the technical detail moved to `docs/dev/` | -| — | — | #42 | Demo reset on every Render boot (`reset-demo.ts`, `DEMO_RESET_ON_BOOT`) | +| — | — | #42 | Demo reset on every Render boot (`reset-demo.ts`, `DEMO_RESET_ON_BOOT`); refined after a deploy race into `prepare-demo.ts`: a boot lock and an idle threshold | | — | — | #43 | VM stack run end to end locally; eight bugs fixed (exec bits, Caddy config, restore format, first-deploy backup, empty `CREDENTIALS_KEY`, stream via the web relay, Redis `noeviction`, health check); VM path removed in the cleanup after #44 | Key behaviours worth knowing (details in `ARCHITECTURE.md`): @@ -606,6 +610,11 @@ follows the plan-first loop above. do). - Nothing alerts on a long open transaction; `/api/metrics` only shows it. - `docs/dev/QUALITY.md` "Before production" lists the deployment-only gaps. +- A deploy during an idle stretch still resets the demo under the container it + replaces, which sees missing tables for the seconds until it is replaced. + Concurrent boots cannot collide (boot lock, `modules/demo/reset.ts`); the + 2026-10-16 deploy that failed with "table public.Operator does not exist" + was two unlocked resets under each other. ## 11. Commands cheat sheet @@ -691,8 +700,9 @@ boot. Kept as a heading only because other notes cite 13b. infrastructure and the UI must keep saying so on every page. - The rate limits are effectively global behind the BFF (already section 10). - Self-approval is allowed: one operator, no roles yet (already section 10). -- The live demo is shared, and every boot resets it, so anything a visitor does - is gone after the service sleeps (`docs/infra/DEPLOYMENT.md` §0). +- The live demo is shared, and a boot after 10 idle minutes resets it, so + anything a visitor does is gone after the service sleeps + (`docs/infra/DEPLOYMENT.md` §0). ### 13d. Dropped, so nobody rebuilds it diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a2ead11..b46c3dc 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -182,8 +182,8 @@ apps/api/ seed-operator.ts one-shot: creates or resets the demo operator seed-demo.ts one-shot: ingests the demo scenario where the demo routes are off (APP_ENV=production); replay-safe - reset-demo.ts one-shot, demo hosts only: drops the schema before a - boot migrates and seeds again (modules/demo/reset.ts) + prepare-demo.ts one-shot, demo hosts only: under a boot lock, resets an + idle demo, migrates and seeds (modules/demo/reset.ts) platform/ cross-cutting plumbing; holds no business rules config/ env parsing (Zod), feature flags @@ -1005,7 +1005,7 @@ sent; a field added to a view by mistake fails the request with a 500. | Wrong client address | `TRUST_PROXY_HOPS` sets how many proxy hops Fastify trusts for the client IP (unset trusts none). The deploy sets 1 | | Clickjacking, sniffing, downgrade | The web app sends `X-Frame-Options: DENY`, `Content-Security-Policy: frame-ancestors 'none'`, `nosniff`, `Referrer-Policy` and HSTS on every response, and no `X-Powered-By` (`next.config.mjs`), so every host sends them, not only one behind a proxy | | Demo endpoints in production | `/api/demo/*` gated behind a flag that is off outside local/demo environments. `APP_ENV=production` refuses to start if `DEMO_ENABLED` is true, the session cookie is not Secure, or `TRUST_PROXY_HOPS` is unset | -| Demo reset wiping a real database | `reset-demo` runs only with both `DEMO_RESET_ON_BOOT=true` and `APP_ENV=production`, and refuses any database holding a lab or event that is not simulated (`modules/demo/reset.ts`) | +| Demo reset wiping a real database, or a demo in use | `prepare-demo` runs only with both `DEMO_RESET_ON_BOOT=true` and `APP_ENV=production`, refuses any database holding a lab or event that is not simulated, keeps a demo with activity in the last `DEMO_RESET_IDLE_MINUTES` (10), and serialises concurrent boots on an advisory lock (`modules/demo/reset.ts`) | --- @@ -1155,7 +1155,7 @@ Phases refer to `docs/specs/labops-copilot/PLAN.md`. | Optional Google sign-in: OIDC code flow, PKCE, exact-email allow-list, `OperatorIdentity` | Done (after Phase 15) | Never run against a real Google client | | Hardening: `APP_ENV=production` startup checks, `TRUST_PROXY_HOPS`, investigation rate limit, security headers from the web app | Done (after Phase 15) | Forward the client address from the web server, so rate limits are per operator | | Free deploy on Render + Neon, single container, live | Done (after Phase 15) | — | -| Demo reset on every boot of the live deploy (`reset-demo`, guarded) | Done (after Phase 15) | — | +| Demo reset on the live deploy when idle, under a boot lock (`prepare-demo`, guarded) | Done (after Phase 15) | — | Build order follows the spec's phases: vertical slice first — simulator → events → correlation → investigation → recovery → verification — so a working diff --git a/CLAUDE.md b/CLAUDE.md index 3307bc6..8ba5983 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -123,7 +123,7 @@ statements. In the api, `npm run coverage` counts unit **and** integration specs together (`vitest.coverage.config.ts`, needs a migrated database), so code that talks to PostgreSQL is measured rather than excluded. Only the process entrypoints (`src/index.ts`, `src/worker.ts`, `src/seed-operator.ts`, -`src/seed-demo.ts`, `src/reset-demo.ts`) are excluded. The web config excludes `src/app/**/*.tsx` (pages and route +`src/seed-demo.ts`, `src/prepare-demo.ts`) are excluded. The web config excludes `src/app/**/*.tsx` (pages and route components), which the Playwright journey covers. Every exclusion carries a comment saying why. Adding exclusions to make a number look better is the same as disabling a test. diff --git a/apps/api/src/modules/demo/reset.ts b/apps/api/src/modules/demo/reset.ts index f7722a2..45a1663 100644 --- a/apps/api/src/modules/demo/reset.ts +++ b/apps/api/src/modules/demo/reset.ts @@ -3,10 +3,15 @@ // first visitor and ages out of the dashboard's windows. The audit trail's // triggers block DELETE and TRUNCATE but not DROP, so this resets the schema, // which is acceptable only for a database that has held nothing but the demo. +// A deploy runs the old and new containers side by side on one database, so +// boots take a lock and a demo in use is kept (docs/infra/DEPLOYMENT.md §0). import type { PrismaClient } from '@prisma/client'; -export type ResetOutcome = 'empty' | 'reset'; +export type ResetOutcome = 'empty' | 'kept' | 'reset'; + +// Any fixed number: it only has to be the same in every boot. +const BOOT_LOCK = 734_501; export class ResetRefused extends Error { constructor(reason: string) { @@ -20,7 +25,22 @@ export function resetAllowed(env: Record): boolean { return env.DEMO_RESET_ON_BOOT === 'true' && env.APP_ENV === 'production'; } -export async function resetDemoDatabase(db: PrismaClient): Promise { +/** + * Runs `step` while holding a database-wide lock, so two containers booting at + * once never interleave reset, migrate and seed. Session-scoped: `db` must use + * a single connection, or the unlock could run on a connection without it. + */ +export async function withBootLock(db: PrismaClient, step: () => Promise): Promise { + await db.$executeRaw`SELECT pg_advisory_lock(${BOOT_LOCK})`; + try { + return await step(); + } finally { + await db.$executeRaw`SELECT pg_advisory_unlock(${BOOT_LOCK})`; + } +} + +/** Resets unless the demo saw activity after `idleSince`: a demo in use stays. */ +export async function resetDemoDatabase(db: PrismaClient, idleSince: Date): Promise { const [{ schema, migrated }] = await db.$queryRaw<[{ schema: string; migrated: boolean }]>` SELECT current_schema() AS schema, to_regclass('"Lab"') IS NOT NULL AS migrated`; if (!migrated) return 'empty'; @@ -33,6 +53,12 @@ export async function resetDemoDatabase(db: PrismaClient): Promise + (SELECT count(*) FROM "OperationalEvent" WHERE source <> 'simulated')::int AS real`; if (real > 0) throw new ResetRefused('the database holds non-simulated data'); + // Waking from sleep means at least 15 idle minutes; a deploy beside a running + // container, or a second boot right after the first, finds recent activity. + const [{ latest }] = await db.$queryRaw<[{ latest: Date | null }]>` + SELECT max("createdAt") AS latest FROM "AuditEntry"`; + if (latest && latest > idleSince) return 'kept'; + await db.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`); await db.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`); return 'reset'; diff --git a/apps/api/src/prepare-demo.ts b/apps/api/src/prepare-demo.ts new file mode 100644 index 0000000..b9a53d7 --- /dev/null +++ b/apps/api/src/prepare-demo.ts @@ -0,0 +1,56 @@ +// One-shot entrypoint for a demo host (deploy/start.sh): under one boot lock, +// reset the demo if it is idle, migrate, seed the operator and the scenario. +// Holding the lock through the seeds is what lets a second container see the +// first one's fresh demo and keep it. See modules/demo/reset.ts. + +import { execFileSync } from 'node:child_process'; +import { createRequire } from 'node:module'; +import { PrismaClient } from '@prisma/client'; +import { z } from 'zod'; +import { resetAllowed, resetDemoDatabase, withBootLock } from './modules/demo/reset.js'; +import { logger } from './platform/observability/logger.js'; + +const prismaCli = createRequire(import.meta.url).resolve('prisma/build/index.js'); + +const prepareEnv = z.object({ + DATABASE_URL: z.url(), + DEMO_RESET_IDLE_MINUTES: z.coerce.number().int().min(0).max(1440).default(10), +}); + +const run = (args: string[]) => execFileSync(process.execPath, args, { stdio: 'inherit' }); + +async function main() { + if (!resetAllowed(process.env)) { + throw new Error('refusing to prepare: needs DEMO_RESET_ON_BOOT=true and APP_ENV=production'); + } + const env = prepareEnv.parse({ + DATABASE_URL: process.env.DATABASE_URL, + DEMO_RESET_IDLE_MINUTES: process.env.DEMO_RESET_IDLE_MINUTES || undefined, + }); + // One connection, so the session lock and its unlock share it. + const url = new URL(env.DATABASE_URL); + url.searchParams.set('connection_limit', '1'); + const db = new PrismaClient({ datasourceUrl: url.toString() }); + try { + await withBootLock(db, async () => { + const idleSince = new Date(Date.now() - env.DEMO_RESET_IDLE_MINUTES * 60_000); + const outcome = await resetDemoDatabase(db, idleSince); + logger.warn({ simulated: true, outcome }, 'demo database reset'); + run([prismaCli, 'migrate', 'deploy']); + run(['dist/seed-operator.js']); + // A failed scenario seed leaves the site serving without it. + try { + run(['dist/seed-demo.js']); + } catch { + logger.error('demo seed failed; serving without it'); + } + }); + } finally { + await db.$disconnect(); + } +} + +main().catch((error: unknown) => { + logger.fatal({ err: error }, 'demo prepare failed'); + process.exitCode = 1; +}); diff --git a/apps/api/src/reset-demo.ts b/apps/api/src/reset-demo.ts deleted file mode 100644 index 8ae72f5..0000000 --- a/apps/api/src/reset-demo.ts +++ /dev/null @@ -1,21 +0,0 @@ -// One-shot entrypoint for a demo host: wipes the database so the boot can -// migrate and seed it fresh (deploy/start.sh). See modules/demo/reset.ts. - -import { prisma } from './db.js'; -import { resetAllowed, resetDemoDatabase } from './modules/demo/reset.js'; -import { logger } from './platform/observability/logger.js'; - -async function main() { - if (!resetAllowed(process.env)) { - throw new Error('refusing to reset: needs DEMO_RESET_ON_BOOT=true and APP_ENV=production'); - } - const outcome = await resetDemoDatabase(prisma); - logger.warn({ simulated: true, outcome }, 'demo database reset'); -} - -main() - .catch((error: unknown) => { - logger.fatal({ err: error }, 'demo reset failed'); - process.exitCode = 1; - }) - .finally(() => prisma.$disconnect()); diff --git a/apps/api/test/integration/modules/demo/reset.int.test.ts b/apps/api/test/integration/modules/demo/reset.int.test.ts index ef18eaf..7888a6a 100644 --- a/apps/api/test/integration/modules/demo/reset.int.test.ts +++ b/apps/api/test/integration/modules/demo/reset.int.test.ts @@ -6,13 +6,24 @@ import { createRequire } from 'node:module'; import { PrismaClient } from '@prisma/client'; import { afterAll, beforeEach, describe, expect, it } from 'vitest'; import { prisma } from '../../../../src/db.js'; -import { ResetRefused, resetDemoDatabase } from '../../../../src/modules/demo/reset.js'; +import { ResetRefused, resetDemoDatabase, withBootLock } from '../../../../src/modules/demo/reset.js'; const prismaCli = createRequire(import.meta.url).resolve('prisma/build/index.js'); const name = `labops_reset_${process.pid}`; const url = new URL(process.env.DATABASE_URL ?? ''); url.pathname = `/${name}`; const scratch = new PrismaClient({ datasourceUrl: url.toString() }); +// A threshold in the future treats any activity as old, so the demo resets. +const always = () => new Date(Date.now() + 60_000); +const singleConnection = () => { + const one = new URL(url); + one.searchParams.set('connection_limit', '1'); + return new PrismaClient({ datasourceUrl: one.toString() }); +}; +const audit = (createdAt?: Date) => + scratch.auditEntry.create({ + data: { actorType: 'system', actorId: 'test', action: 'scenario.run', targetType: 'scenario', targetId: 's', outcome: 'created', createdAt }, + }); const migrate = () => execFileSync(process.execPath, [prismaCli, 'migrate', 'deploy'], { @@ -36,17 +47,15 @@ afterAll(async () => { describe('resetDemoDatabase', () => { it('leaves a never-migrated database alone', async () => { - expect(await resetDemoDatabase(scratch)).toBe('empty'); + expect(await resetDemoDatabase(scratch, always())).toBe('empty'); }); it('drops a demo database completely, audit trail included, so it can migrate again', async () => { migrate(); await scratch.lab.create({ data: { name: 'demo-lab' } }); - await scratch.auditEntry.create({ - data: { actorType: 'system', actorId: 'test', action: 'scenario.run', targetType: 'scenario', targetId: 's', outcome: 'created' }, - }); + await audit(); - expect(await resetDemoDatabase(scratch)).toBe('reset'); + expect(await resetDemoDatabase(scratch, always())).toBe('reset'); expect(await tableExists('"Lab"')).toBe(false); expect(await tableExists('"AuditEntry"')).toBe(false); @@ -55,12 +64,52 @@ describe('resetDemoDatabase', () => { expect(await scratch.lab.count()).toBe(0); }); + // A deploy starts a new container beside one that is serving: the demo in + // use must survive the new container's boot. + it('keeps a demo with activity after the idle threshold', async () => { + migrate(); + await scratch.lab.create({ data: { name: 'demo-lab' } }); + await audit(); + + expect(await resetDemoDatabase(scratch, new Date(Date.now() - 10 * 60_000))).toBe('kept'); + expect(await scratch.lab.count()).toBe(1); + }); + + it('resets a demo whose last activity is older than the threshold', async () => { + migrate(); + await audit(new Date(Date.now() - 60 * 60_000)); + + expect(await resetDemoDatabase(scratch, new Date(Date.now() - 10 * 60_000))).toBe('reset'); + }); + // Negative: a database holding anything a provider sent is not a demo. it('refuses to wipe a database with non-simulated data, and leaves it intact', async () => { migrate(); await scratch.lab.create({ data: { name: 'real-lab', source: 'provider' } }); - await expect(resetDemoDatabase(scratch)).rejects.toBeInstanceOf(ResetRefused); + await expect(resetDemoDatabase(scratch, always())).rejects.toBeInstanceOf(ResetRefused); expect(await scratch.lab.count()).toBe(1); }); }); + +describe('withBootLock', () => { + // Negative: two containers booting at once must never interleave. Without the + // lock one reset dropped the tables between the other's migrate and seed. + it('runs two boots one after the other, never together', async () => { + const [a, b] = [singleConnection(), singleConnection()]; + const spans: Array<[number, number]> = []; + const boot = (db: PrismaClient) => + withBootLock(db, async () => { + const start = Date.now(); + await new Promise((resolve) => setTimeout(resolve, 300)); + spans.push([start, Date.now()]); + }); + try { + await Promise.all([boot(a), boot(b)]); + } finally { + await Promise.all([a.$disconnect(), b.$disconnect()]); + } + const [first, second] = spans.sort((x, y) => x[0] - y[0]); + expect(second[0]).toBeGreaterThanOrEqual(first[1]); + }); +}); diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index ddc4dc2..8bb0541 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ 'src/worker.ts', 'src/seed-operator.ts', 'src/seed-demo.ts', - 'src/reset-demo.ts', + 'src/prepare-demo.ts', ], thresholds: { lines: 70, diff --git a/deploy/start.sh b/deploy/start.sh index 6eb1dd1..4c95ead 100755 --- a/deploy/start.sh +++ b/deploy/start.sh @@ -28,13 +28,16 @@ stop() { kill $worker $api $web 2>/dev/null || true; } trap 'stop; wait; exit 0' TERM INT cd /repo/apps/api -# A shared demo stays resolved after its first visitor and ages out of the -# dashboard's windows, so a demo host starts every boot from an empty database. +# A demo host resets an idle demo, migrates and seeds under one boot lock, so a +# deploy's overlapping containers cannot interleave (dist/prepare-demo.js). if [ "${DEMO_RESET_ON_BOOT:-}" = true ]; then - node dist/reset-demo.js + node dist/prepare-demo.js +else + node /repo/node_modules/prisma/build/index.js migrate deploy + node dist/seed-operator.js + # Replays add nothing; a failure leaves the site serving without the demo. + node dist/seed-demo.js || echo 'demo seed failed; serving without it' >&2 fi -node /repo/node_modules/prisma/build/index.js migrate deploy -node dist/seed-operator.js node --max-old-space-size="$WORKER_HEAP" dist/worker.js & worker=$! @@ -44,9 +47,6 @@ api=$! /repo/node_modules/next/dist/bin/next start -p "${PORT:-10000}" -H 0.0.0.0) & web=$! -# Replays add nothing, so every boot seeds; a failure leaves the site serving. -node dist/seed-demo.js || echo 'demo seed failed; serving without it' >&2 - # Any one process stopping takes the container down, so the platform restarts # all three together rather than serving a site with a dead worker. while kill -0 "$worker" 2>/dev/null && kill -0 "$api" 2>/dev/null && kill -0 "$web" 2>/dev/null; do diff --git a/docs/GAPS.md b/docs/GAPS.md index 2097965..6a5f6c5 100644 --- a/docs/GAPS.md +++ b/docs/GAPS.md @@ -106,8 +106,9 @@ platform. The *action* would not. - **No alerting or notification of any kind.** No email, no chat integration, no webhook outbound. An incident created at 2am is visible only to whoever opens the dashboard. `/api/metrics` reports a long open transaction if someone looks. -- **No backups.** The live deploy has no backup step, by design: every boot - wipes and reseeds its demo database, so there is nothing to keep. +- **No backups.** The live deploy has no backup step, by design: a boot after + 10 idle minutes wipes and reseeds its demo database, so there is nothing to + keep. ## 4. Data handling @@ -174,10 +175,11 @@ platform. The *action* would not. - **It sleeps after 15 minutes without a request**, worker included. The first visit after that waits for a cold boot (about 2.5 minutes, measured locally under the same 0.1 CPU cap, not on the host). -- **The demo resets on every boot.** Each boot (a wake from sleep or a redeploy) - drops and reseeds the demo database (`DEMO_RESET_ON_BOOT`), so anything a - visitor did is gone after the service sleeps. Every visitor shares the one - `demo` login. +- **The demo resets when idle.** A boot after 10 idle minutes (every wake from + sleep) drops and reseeds the demo database (`DEMO_RESET_ON_BOOT`), so + anything a visitor did is gone after the service sleeps. A deploy during + that idle stretch resets it too, under the container being replaced. Every + visitor shares the one `demo` login. - **The demo's AI is the fixture**, not a model (`LLM_PROVIDER=fixture`), so every investigation on the live site is identical by design. - **Render deploys from `main` only after every CI check passes**, including a diff --git a/docs/dev/QUALITY.md b/docs/dev/QUALITY.md index c0f8074..d6ca770 100644 --- a/docs/dev/QUALITY.md +++ b/docs/dev/QUALITY.md @@ -98,7 +98,7 @@ done. | 13 | Integration settings and sealed secrets, adapter-gated (no live connector: the gate is closed) | | 14 | Browser journey in CI, measured metrics | | 15 | Delivery: one incident as one trace, the opt-in trace viewer, this walkthrough | -| After 15 | Optional Google sign-in; the free live deploy on Render and Neon, reset on every boot ([`docs/infra/DEPLOYMENT.md`](../infra/DEPLOYMENT.md) §0); security headers from the web app | +| After 15 | Optional Google sign-in; the free live deploy on Render and Neon, reset when idle ([`docs/infra/DEPLOYMENT.md`](../infra/DEPLOYMENT.md) §0); security headers from the web app | --- diff --git a/docs/dev/SETUP.md b/docs/dev/SETUP.md index da4bcdb..23dbae8 100644 --- a/docs/dev/SETUP.md +++ b/docs/dev/SETUP.md @@ -194,7 +194,7 @@ labops-copilot/ │ │ ├── prisma/ Data model and migrations │ │ ├── src/ │ │ │ ├── index.ts, worker.ts, app.ts Entrypoints: start here -│ │ │ ├── seed-operator.ts, seed-demo.ts, reset-demo.ts One-shot jobs +│ │ │ ├── seed-operator.ts, seed-demo.ts, prepare-demo.ts One-shot jobs │ │ │ ├── platform/ Cross-cutting: config, http, auth, audit, │ │ │ │ observability, secrets, jobs, events-stream │ │ │ └── modules/ One folder per feature: labs, events, @@ -243,7 +243,7 @@ labops-copilot/ | `npm run seed:operator -w @labops/api` | Create or reset the operator from `SEED_OPERATOR_*` | | `npm run seed:demo -w @labops/api` | Ingest the demo scenario where demo routes are off; safe to re-run | | `scripts/clean-db-check.sh` | Integration tests twice on a throwaway database, then drop it | -| `scripts/deploy-image-smoke.sh` | Build the live deploy's image and boot it twice under 512 MB, as CI does before Render may deploy | +| `scripts/deploy-image-smoke.sh` | Build the live deploy's image; boot two containers at once on one database (one resets, one keeps), then one past the idle threshold (it resets), under 512 MB, as CI does before Render may deploy | ### Checks before you commit diff --git a/docs/infra/DEPLOYMENT.md b/docs/infra/DEPLOYMENT.md index 7a3eb94..6dfc517 100644 --- a/docs/infra/DEPLOYMENT.md +++ b/docs/infra/DEPLOYMENT.md @@ -49,15 +49,23 @@ memory figures below were measured locally under the same caps, not on the host. - **Any process exiting stops the container**, so the platform restarts all three together rather than serving a site whose worker is dead. - **750 free hours a month**, shared: exactly one always-on service fits. -- **Every boot starts from an empty database** (`DEMO_RESET_ON_BOOT=true` in - `render.yaml`): `dist/reset-demo.js` drops the schema, then the boot migrates - and seeds. A shared demo would otherwise stay resolved after its first - visitor and age out of the dashboard's 7-day window. Anything a visitor did - is gone after the service sleeps, so there is nothing to back up. The reset - needs both `DEMO_RESET_ON_BOOT` and `APP_ENV=production`, and refuses, - failing the boot, if any lab or event is not simulated; it drops the schema - because the audit trail's triggers block deleting rows +- **A boot resets an idle demo** (`DEMO_RESET_ON_BOOT=true` in `render.yaml`): + `dist/prepare-demo.js` drops the schema if nothing was audited in the last + `DEMO_RESET_IDLE_MINUTES` (10), then migrates and seeds. Waking from sleep + means at least 15 idle minutes, so every wake starts fresh; a deploy beside a + container in use keeps the demo. A shared demo would otherwise stay resolved + after its first visitor and age out of the dashboard's 7-day window. Anything + a visitor did is gone after the service sleeps, so there is nothing to back + up. The reset needs both `DEMO_RESET_ON_BOOT` and `APP_ENV=production`, and + refuses, failing the boot, if any lab or event is not simulated; it drops the + schema because the audit trail's triggers block deleting rows (`apps/api/src/modules/demo/reset.ts`). +- **Boots take a lock.** A deploy runs the new container beside the live one on + the same database. Reset, migrate and both seeds run under one Postgres + advisory lock, so two boots never interleave; the second sees the first's + fresh demo and keeps it. Without the lock, the 2026-10-16 deploy failed: each + reset dropped the schema under the other, and the new container's operator + seed found no `Operator` table. **Standing it up:** @@ -149,6 +157,7 @@ The rest is in `docs/GAPS.md`. 1. Read `AGENTS.md` and `CLAUDE.md`. `AGENTS.md` §13 is the current task list. 2. Read `docs/GAPS.md` before describing this project's capabilities to anyone. -3. A push to `main` goes live once its CI passes, and every boot resets the demo. +3. A push to `main` goes live once its CI passes, and a boot after 10 idle + minutes resets the demo. 4. The open item is Google sign-in against a real OAuth client (`AGENTS.md` §13a): every test so far stubs Google. diff --git a/docs/infra/INFRA.md b/docs/infra/INFRA.md index ff217f8..a6e2c19 100644 --- a/docs/infra/INFRA.md +++ b/docs/infra/INFRA.md @@ -118,7 +118,8 @@ reach another project's instance. | `NEXT_PUBLIC_API_URL` | web | `http://localhost:4000` | API URL fallback (URLs only, never tokens) | | `SESSION_COOKIE_SECURE` | web | `true` (`false` in compose) | The web origin's session cookie only over https; off only for local http | | `API_INTERNAL_URL` | web | falls back to `NEXT_PUBLIC_API_URL` | API URL for server-side rendering | -| `DEMO_RESET_ON_BOOT` | Render boot | unset | `true` in `render.yaml` only: each boot drops and reseeds the demo database. Also needs `APP_ENV=production`; refuses non-simulated data | +| `DEMO_RESET_ON_BOOT` | Render boot | unset | `true` in `render.yaml` only: `prepare-demo.js` runs reset, migrate and seeds under a boot lock, dropping and reseeding the demo database when idle. Also needs `APP_ENV=production`; refuses non-simulated data | +| `DEMO_RESET_IDLE_MINUTES` | Render boot (`prepare-demo.js`) | `10` | 0 to 1440. A demo with an audit entry newer than this is kept; waking from sleep is always older. The deploy image smoke sets 0 to force a reset | | `API_HEAP_MB`, `WORKER_HEAP_MB`, `WEB_HEAP_MB` | Render boot | `128`, `128`, `160` | Per-process heap caps so three Node processes fit in 512 MB | | `PORT`, `RENDER_EXTERNAL_URL` | Render boot | set by Render | The web app listens on `PORT`; `CORS_ORIGIN` falls back to `RENDER_EXTERNAL_URL` | @@ -149,7 +150,8 @@ than the code: the free tier returns 503 under load, and retired models answer - Schema changes are checked-in migrations in `apps/api/prisma/migrations`, applied with `prisma migrate deploy` everywhere: `npm run db:migrate` locally, the `integration-test` CI job, the compose `migrate` service, and - `deploy/start.sh` on every boot of the live deploy. + `deploy/start.sh` on every boot of the live deploy (inside the boot lock, + via `prepare-demo.js`). - New migration: edit `schema.prisma`, then `npm run prisma:migrate:dev -w @labops/api -- --name `. Raw SQL for partial unique indexes, `CHECK` constraints and triggers goes in the @@ -225,7 +227,7 @@ a running stack with `scripts/compose-smoke.sh`. The api coverage job runs unit and integration specs together against a migrated Postgres service container, so database code is measured, not excluded; only the process entrypoints (`src/index.ts`, `src/worker.ts`, -`src/seed-operator.ts`, `src/seed-demo.ts`, `src/reset-demo.ts`) are left out. The web job +`src/seed-operator.ts`, `src/seed-demo.ts`, `src/prepare-demo.ts`) are left out. The web job excludes server components, which only E2E can reach. **Known gaps** @@ -261,11 +263,11 @@ a dashboard setting cannot contradict the production checks. **Deploying.** Render deploys a push to `main` once every CI check on it passes, the deploy image smoke included; there is no manual step and no image -registry. Migrations run at boot, before the processes start, -which is safe because every boot also starts from an empty demo database. +registry. Migrations run at boot, before the processes start, inside the boot +lock, so a deploy's overlapping containers never migrate or reset at once. -**Backups and secrets.** There are no backups: every boot wipes and reseeds the -demo database, so it never holds anything worth keeping. Secrets +**Backups and secrets.** There are no backups: a boot after 10 idle minutes +wipes and reseeds the demo database, so it never holds anything worth keeping. Secrets (`DATABASE_URL`, `SEED_OPERATOR_PASSWORD`) are service variables in the Render dashboard, and Render generates `CREDENTIALS_KEY`. diff --git a/docs/specs/labops-copilot/PLAN.md b/docs/specs/labops-copilot/PLAN.md index 86620f2..f830e27 100644 --- a/docs/specs/labops-copilot/PLAN.md +++ b/docs/specs/labops-copilot/PLAN.md @@ -535,6 +535,11 @@ Work that followed the phases, one pull request each: `docs/dev/`. - **#42 Demo reset on every Render boot:** `reset-demo.ts`, so a shared demo never stays resolved or ages out of the dashboard. +- **The reset made deploy-safe:** a deploy overlaps two containers on one + database, and two unlocked resets failed one on 2026-10-16. `prepare-demo.ts` + now resets only an idle demo (10 minutes) and runs reset, migrate and seeds + under a Postgres advisory lock; the deploy image smoke boots two containers + at once to prove it. - **#43 The self-hosted stack made to work:** run end to end locally for the first time; six blocking bugs fixed. - **Afterwards: the self-hosted stack removed.** The VM path (#38, #43) went, diff --git a/render.yaml b/render.yaml index 24d09c8..c324471 100644 --- a/render.yaml +++ b/render.yaml @@ -35,9 +35,10 @@ services: generateValue: true - key: LLM_PROVIDER value: fixture - # Wipes the database on every boot (deploy/start.sh), so each - # session after the service sleeps starts from a fresh demo. Demo only: - # the reset refuses any database holding non-simulated data. + # Each boot resets the demo if it has been idle 10 minutes, so every wake + # from sleep starts fresh while a deploy beside a running container keeps + # it; boots take a lock (deploy/start.sh). Demo only: the reset refuses + # any database holding non-simulated data. - key: DEMO_RESET_ON_BOOT value: "true" diff --git a/scripts/deploy-image-smoke.sh b/scripts/deploy-image-smoke.sh index acbf13d..7328ca9 100755 --- a/scripts/deploy-image-smoke.sh +++ b/scripts/deploy-image-smoke.sh @@ -1,8 +1,9 @@ #!/usr/bin/env bash # Builds the live deploy's image (deploy/Dockerfile) and boots it the way the # host does: 512 MB, the demo reset on, against a throwaway PostgreSQL and -# Redis. Then restarts it, so the reset of a seeded database is exercised too. -# CI runs this before Render may deploy; it runs the same on a laptop. +# Redis. Two containers start at once on one database, as during a deploy, and +# both must serve one demo; then a container past the idle threshold must reset +# it. CI runs this before Render may deploy; it runs the same on a laptop. set -euo pipefail cd "$(dirname "$0")/.." @@ -12,9 +13,10 @@ IMAGE="${NAME}:test" PORT="${SMOKE_PORT:-10001}" # Throwaway credentials for containers that live only for this run. OPERATOR_PASSWORD="$(openssl rand -hex 16)" +CREDENTIALS_KEY="$(openssl rand -base64 32)" cleanup() { - docker rm -f "${NAME}-app" "${NAME}-pg" "${NAME}-redis" >/dev/null 2>&1 || true + docker rm -f "${NAME}-a" "${NAME}-b" "${NAME}-c" "${NAME}-pg" "${NAME}-redis" >/dev/null 2>&1 || true docker network rm "$NAME" >/dev/null 2>&1 || true docker image rm "$IMAGE" >/dev/null 2>&1 || true } @@ -22,14 +24,18 @@ trap cleanup EXIT # Captured, then searched: with pipefail, `docker logs | grep -q` fails when # grep exits at its first match and the writer is cut off. -app_logs() { docker logs "${NAME}-app" 2>&1; } +logs_of() { docker logs "${NAME}-$1" 2>&1; } fail() { echo "FAILED: $1" >&2 - docker logs --tail 60 "${NAME}-app" >&2 2>/dev/null || true + for app in a b c; do + docker logs --tail 40 "${NAME}-${app}" >&2 2>/dev/null || true + done exit 1 } +sql() { docker exec "${NAME}-pg" psql -U labops -d labops -tAc "$1"; } + echo "==> building deploy/Dockerfile" docker build -q -f deploy/Dockerfile -t "$IMAGE" . >/dev/null @@ -41,52 +47,54 @@ docker run -d --name "${NAME}-redis" --network "$NAME" \ redis:7-alpine redis-server --maxmemory-policy noeviction >/dev/null until docker exec "${NAME}-pg" pg_isready -U labops >/dev/null 2>&1; do sleep 1; done -echo "==> booting it as the host does (512 MB, demo reset on)" -docker run -d --name "${NAME}-app" --network "$NAME" \ - --memory=512m --memory-swap=512m -p "${PORT}:10000" \ - -e DATABASE_URL="postgresql://labops:labops@${NAME}-pg:5432/labops" \ - -e REDIS_URL="redis://${NAME}-redis:6379" \ - -e RENDER_EXTERNAL_URL="http://localhost:${PORT}" \ - -e SEED_OPERATOR_USERNAME=demo -e SEED_OPERATOR_PASSWORD="$OPERATOR_PASSWORD" \ - -e CREDENTIALS_KEY="$(openssl rand -base64 32)" \ - -e LLM_PROVIDER=fixture -e DEMO_RESET_ON_BOOT=true \ - "$IMAGE" >/dev/null +# Starts container `$1` on host port `$2`; extra arguments are docker env flags. +boot() { + local app="$1" port="$2"; shift 2 + docker run -d --name "${NAME}-${app}" --network "$NAME" \ + --memory=512m --memory-swap=512m -p "${port}:10000" \ + -e DATABASE_URL="postgresql://labops:labops@${NAME}-pg:5432/labops" \ + -e REDIS_URL="redis://${NAME}-redis:6379" \ + -e RENDER_EXTERNAL_URL="http://localhost:${port}" \ + -e SEED_OPERATOR_USERNAME=demo -e SEED_OPERATOR_PASSWORD="$OPERATOR_PASSWORD" \ + -e CREDENTIALS_KEY="$CREDENTIALS_KEY" \ + -e LLM_PROVIDER=fixture -e DEMO_RESET_ON_BOOT=true \ + "$@" "$IMAGE" >/dev/null +} -# Waits until the boot has seeded the demo `count` times in total. -wait_for_seed() { - local count="$1" +# Waits until container `$1` serves the login page with the API reachable. +wait_serving() { + local app="$1" port="$2" page for _ in $(seq 1 120); do - [ "$(docker inspect -f '{{.State.Running}}' "${NAME}-app")" = true ] || fail "the container exited" - logs="$(app_logs)" - if [ "$(grep -c 'demo scenario seeded' <<<"$logs")" -ge "$count" ]; then - return 0 - fi + [ "$(docker inspect -f '{{.State.Running}}' "${NAME}-${app}")" = true ] || fail "container ${app} exited" + page="$(curl -s "http://localhost:${port}/login" || true)" + if grep -Eq 'API: ()?ok' <<<"$page"; then return 0; fi sleep 2 done - fail "the demo was not seeded within four minutes" + fail "container ${app} did not serve within four minutes" } -check_site() { - local status - status="$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:${PORT}/login")" - [ "$status" = 200 ] || fail "the login page answered ${status}" - local page - page="$(curl -s "http://localhost:${PORT}/login")" - grep -Eq 'API: ()?ok' <<<"$page" || fail "the web app cannot reach the API" -} +outcome_of() { grep -oE '"outcome":"(empty|kept|reset)"' <<<"$(logs_of "$1")" | head -1 | cut -d'"' -f4; } -wait_for_seed 1 -grep -q '"outcome":"empty"' <<<"$(app_logs)" || fail "the first boot did not see an empty database" -check_site +echo "==> two containers boot at once on one empty database, as during a deploy" +boot a "$PORT" +boot b "$((PORT + 1))" +wait_serving a "$PORT" +wait_serving b "$((PORT + 1))" +outcomes="$(printf '%s\n%s\n' "$(outcome_of a)" "$(outcome_of b)" | sort | tr '\n' ' ')" +[ "$outcomes" = "empty kept " ] || fail "expected one empty and one kept boot, got: ${outcomes}" +labs="$(sql 'SELECT count(*) FROM "Lab"')" +[ "$labs" = 40 ] || fail "expected the 40 demo labs once, found ${labs}" head="$(curl -sI "http://localhost:${PORT}/login")" headers="$(grep -ciE '^(x-frame-options|content-security-policy|x-content-type-options|referrer-policy|strict-transport-security):' <<<"$head")" [ "$headers" = 5 ] || fail "expected 5 security headers, got ${headers}" -echo "ok: first boot seeded, login 200, API ok, 5 security headers" +echo "ok: one boot reset, the other kept it; both serve; 40 labs; 5 security headers" -echo "==> restarting: the boot must reset the seeded database and come back" -docker restart "${NAME}-app" >/dev/null -wait_for_seed 2 -grep -q '"outcome":"reset"' <<<"$(app_logs)" || fail "the restart did not reset the demo" -check_site -echo "ok: restart reset the demo and the site came back" -echo "ok: $(docker stats --no-stream --format '{{.MemUsage}}' "${NAME}-app") in use" +echo "==> after both stop, a boot past the idle threshold resets the demo" +docker rm -f "${NAME}-a" "${NAME}-b" >/dev/null +boot c "$PORT" -e DEMO_RESET_IDLE_MINUTES=0 +wait_serving c "$PORT" +[ "$(outcome_of c)" = reset ] || fail "expected the idle demo to reset, got: $(outcome_of c)" +labs="$(sql 'SELECT count(*) FROM "Lab"')" +[ "$labs" = 40 ] || fail "expected a fresh 40 labs after the reset, found ${labs}" +echo "ok: the idle demo reset and the site came back" +echo "ok: $(docker stats --no-stream --format '{{.MemUsage}}' "${NAME}-c") in use"