Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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`):
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`) |

---

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
30 changes: 28 additions & 2 deletions apps/api/src/modules/demo/reset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -20,7 +25,22 @@ export function resetAllowed(env: Record<string, string | undefined>): boolean {
return env.DEMO_RESET_ON_BOOT === 'true' && env.APP_ENV === 'production';
}

export async function resetDemoDatabase(db: PrismaClient): Promise<ResetOutcome> {
/**
* 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<T>(db: PrismaClient, step: () => Promise<T>): Promise<T> {
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<ResetOutcome> {
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';
Expand All @@ -33,6 +53,12 @@ export async function resetDemoDatabase(db: PrismaClient): Promise<ResetOutcome>
+ (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';
Expand Down
56 changes: 56 additions & 0 deletions apps/api/src/prepare-demo.ts
Original file line number Diff line number Diff line change
@@ -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;
});
21 changes: 0 additions & 21 deletions apps/api/src/reset-demo.ts

This file was deleted.

63 changes: 56 additions & 7 deletions apps/api/test/integration/modules/demo/reset.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'], {
Expand All @@ -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);
Expand All @@ -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]);
});
});
2 changes: 1 addition & 1 deletion apps/api/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
16 changes: 8 additions & 8 deletions deploy/start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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=$!
Expand All @@ -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
Expand Down
Loading
Loading