Files
fusion/scripts/boot-smoke.mjs
gsxdsm c15c78feeb feat: migrate storage from SQLite to PostgreSQL (#1793)
# Migrate storage from SQLite to PostgreSQL — full dashboard cutover

Migrates Fusion's storage layer to the embedded PostgreSQL
`AsyncDataLayer` (the default backend) and **completes the
satellite-store + feature cutover** so every dashboard and Command
Center surface works in PG mode.

## Status — every surface works in embedded-PG mode

Verified live against a running embedded-Postgres dashboard (all
**200**, zero 5xx) and gate-tested (**23 files / 99 tests** on embedded
PG, plus engine-core 294 and ci-shape 63 in the blocking merge gate;
core/engine/cli/dashboard typecheck clean).

| Area | Surfaces | State |
|---|---|---|
| Satellite stores | workflows, todos, insights, research, missions,
goals, mailbox | ✅ |
| Views | artifacts, documents, evals | ✅ |
| Command Center | activity, productivity, team, tokens, tools,
**workflows**, **github**, **signals**, **plugin-activations**, **live**
(all 10) | ✅ |
| Run execution | insight generation, research run execution | ✅
(store-path; AI step needs a provider) |
| Live updates | SSE push for mission/research/insight events | ✅ |
| Workflow editing | create / update / delete / select (+ id counter) |
✅ |
| Engine | mission autopilot, incident-signal ingestion, regression
storm-guard, agent wake-on-message | ✅ |
| Core | tasks, agents, secrets, automations, memory, chat, usage, PRs,
git | ✅ |

## Approach

Each satellite store gets an `Async<Store>` wrapper exposing the sync
store's method names over the existing `async-*-store.ts` helpers;
`get<Store>Store()` returns a `Sync | Async` union; consumers `await`
(harmless on sync), and engine/CLI paths that can't convert use
`instanceof Sync` graceful fallback. Analytics aggregators branch on
`"ping" in dbOrLayer` to run schema-qualified raw SQL over `project.*`
(snake_case) in PG. Executors/orchestrators/autopilot are
await-converted to drive the union store; the async store wrappers
extend `EventEmitter` so SSE live-push fires in both backends.

Not-yet-ported capabilities degrade gracefully (never 500) and are
individually called out in commits.

## Sync with main

The branch is kept continuously merged with `main` (currently through
FN-7845, 2026-07-12); the earlier "final rebase deferred" note no longer
applies. Use **Create a merge commit** (or squash) to land it — GitHub's
rebase-merge cannot replay a merge-maintained branch.

## Residual Review Findings

Multi-agent code review of the PostgreSQL satellite-store ports (U1–U5)
applied 3 safe fixes (see `fix(review): apply autofix feedback`). The
following are **real but gated** — recorded here as follow-up work
rather than auto-applied. All are SQLite→PostgreSQL
**concurrency/atomicity regressions**: the sync stores were immune only
by SQLite's single-writer, single-threaded-handler execution; the async
ports open multi-await read-modify-write windows. **Reachability is low
today** because the execution engines that generate concurrent same-run
mutations (insight run executor, research orchestrator/dispatcher) are
`instanceof`-gated to sync mode in PG. No process-crash class survived
(all engine fallbacks correctly guard the sync store).

- **[P1] Research `appendResearchEvent` dual-write is non-atomic**
(`packages/core/src/async-research-store.ts`, corroborated: adversarial
+ reliability). The `research_run_events` insert (own transaction) and
the `run.events` jsonb update are separate writes — a crash between
them, or two concurrent appends, splits the table count from the jsonb
array. **Fix:** perform the seq-insert and the jsonb update in one
`layer.transactionImmediate`.
- **[P1] Research run terminal-reversion via stale full-row persist**
(`async-research-store.ts` `persistResearchRun`/`updateResearchStatus`).
Concurrent `PATCH /runs/:id/status` + `POST /runs/:id/events` can revert
a terminal run to `running` by overwriting the whole row, bypassing the
transition guard. **Fix:** scoped column `UPDATE`s with a `WHERE status
…` guard, or optimistic version column.
- **[P2] `updateResearchRun`/`updateInsightRun` read-then-write TOCTOU**
— concurrent PATCHes last-writer-wins on the lifecycle merge. **Fix:**
`SELECT … FOR UPDATE` / enclosing transaction.
- **[P2] `upsertRun`/`createRunOrThrowConflict` check-then-create race**
(`async-insight-store.ts`) — two callers can each create an "active"
run. **Fix:** partial unique index on `(projectId, trigger) WHERE status
IN ('pending','running')`.
- **[P3] `createResearchRetryRun` return-value divergence** — sync
returns the pre-update `queued` snapshot; async returns the reloaded
`retry_waiting` run (persisted state is identical). Pick one side for
cross-backend parity.
- **[P2/perf] Mission `getMissionWithHierarchy`/`getMissionHealth` N+1
fan-out** — O(milestones×slices) sequential round-trips hold one pool
slot per request; can starve the pool for large hierarchies. **Fix:**
batched/joined reads.
- **Testing gaps:** no PG-mode concurrency tests (interleaved
status/event mutations), no sync↔async parity assertion for the
lifecycle-error codes, and no mission status/health rollup parity test
vs the sync `MissionStore`.

~~Out of scope (deferred): AI run *execution* (insight/research) +
mission autopilot + live SSE mission events remain sync-gated/degraded
in PG mode.~~ **Since ported** — insight/research run execution, mission
autopilot, and SSE live push all run on the async layer now, which also
makes the concurrency findings above genuinely reachable; they remain
open follow-ups.







---

## Update — 2026-07-12: production-readiness hardening & live acceptance

Everything below landed on this branch since the description above was
written:

**Production blockers from review — fixed**
- `recoverStaleTransitionPending` ported to the async layer (backend
moves write + clear the crash-safe marker; startup/maintenance sweeps no
longer throw).
- Lost-update class fixed: `atomicWriteTaskJson`/`WithAudit` write
changed columns only (full-row upserts silently resurrected stale fields
across concurrent store instances — the "task stuck unplanned forever"
bug).
- First-boot **auto-migration**: booting the PG backend over a project
with a legacy `fusion.db` migrates it automatically (loud failure,
SQLite kept as backup), and the dashboard shows a one-time **"your data
was migrated" banner** with the backup paths and a Need-help Discord
link.
- `pg_dump`/`pg_restore` discovered from common install locations for
embedded-mode backups.
- The PG suite is part of the blocking merge gate (`test:pg-gate`).

**Multi-project isolation (PR #2007, merged into this branch)**
- `project_id` partition key on tasks / archived tasks / config,
`taskProjectScope` threaded through every scan/claim/count, per-project
config rows, layer bound to the project at startup.
- Review P1 follow-up: the shared cold-storage `archive.archived_tasks`
table is also partitioned and all archived-board reads/counts/searches
are scoped.
- Schema drift self-heal generalized to schema-qualified columns so
existing databases upgrade in place.

**Other changes**
- Node settings sync **removed** in PG mode (409
`settings-sync-disabled-postgres`) — nodes share state by connecting to
the same database; auth sync kept (per-machine file).
- Perf (review findings): `listTasks` pushes column filter + ORDER BY +
LIMIT/OFFSET into SQL; `getConversation` capped to the most recent 200
messages.
- Fixed a false "operator action required" pause-abort log fired on
every successfully auto-merged task.

**Live acceptance — PASSED (2026-07-12)**
A sandboxed instance (isolated HOME, embedded PG, real Opus executor)
ran a task through the complete cycle: create → triage (AI spec) →
execute → in-review → AI squash-merge landed on the project's `main` →
done. A write+read sweep of every data surface (settings, comments,
documents, attachments + artifact bridge + artifact edit, chat with real
generation, goals, missions, agent mail, secrets, workflows, memory, CC
analytics) was green on embedded PG.

**Known remaining work**
- The per-project `config` PK re-key has no upgrade path for
pre-isolation embedded-PG databases (needs a real `DROP
CONSTRAINT`/re-key migration; fresh databases are fine).
- `pg_dump`/`pg_restore` binaries are not yet bundled in release
artifacts (PATH/common-location discovery only).
- The satellite-store concurrency findings listed above.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Phil Larson <hello@phillarson.xyz>
Co-authored-by: fusion-merge <fusion-merge@local>
2026-07-13 19:07:58 -07:00

299 lines
12 KiB
JavaScript

#!/usr/bin/env node
/**
* Boot smoke check — the merge gate's "the app starts and serves" proof.
*
* Verifies, against the *built* workspace (run `pnpm build` first):
* 1. The CLI answers `--help` with exit 0.
* 2. `fn serve` boots a real HTTP server on an ephemeral port and
* GET /api/health returns 200 within the timeout.
* 3. The server shuts down cleanly on SIGTERM.
*
* Safety properties (see scripts/check-no-kill-4040.mjs and AGENTS.md):
* (port-4040-allowlist: this file only ever AVOIDS the reserved ports — it
* requests an ephemeral port and rejects reserved ones; it never binds,
* probes, or kills them.)
* (process-supervisor-allowlist: raw spawn is intentional here — this is a
* standalone repo script outside the package graph, the child is attached
* (not detached), and lifecycle is bounded by the timeouts + signal handlers
* below; importing superviseSpawn from @fusion/core would invert the
* dependency direction for a build-time smoke check.)
* - Never binds or touches port 4040 / FUSION_RESERVED_PORTS — an ephemeral
* port is requested from the OS (listen on 0) and double-checked against
* the reserved list.
* - Never kills anything except the child process it spawned itself.
* - Runs with an isolated $HOME and throwaway cwd project (mkdtemp) so it
* cannot read or corrupt a developer's real fusion.db, task artifacts, or auth state.
*
* Exit code is the verdict: 0 = boots and serves, non-zero = broken, with
* captured child stderr on stdout for CI logs.
*/
import { spawn, spawnSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const cliBin = path.join(repoRoot, "packages/cli/bin.mjs");
// FNXC:BackendFlip 2026-06-26-14:50:
// The boot smoke exercises the embedded PostgreSQL backend by default. This
// is the zero-config production path post default-flip: with DATABASE_URL
// unset and no FUSION_NO_EMBEDDED_PG opt-out, the startup factory boots the
// bundled embedded PG. The first run pays a one-time initdb cost (writing the
// cluster data directory), which can take well over a minute on a cold
// filesystem/CI runner. The health-check timeout is therefore generous so
// the merge gate does not flake on the embedded initdb cost.
//
// DATABASE_URL is explicitly unset in the child env so a developer's real
// external DB connection string can never leak into the smoke and change the
// backend under test. FUSION_NO_EMBEDDED_PG is also explicitly unset so the
// smoke always exercises the embedded default (it cannot be opted out by an
// inherited env var).
const HEALTH_TIMEOUT_MS = 180_000;
const SHUTDOWN_TIMEOUT_MS = 15_000;
// Ephemeral-port TOCTOU: retry the whole boot with a fresh port when the
// child loses the bind race (EADDRINUSE).
const BOOT_ATTEMPTS = 3;
function parsePortList(raw) {
return String(raw ?? "")
.split(",")
.map((p) => Number.parseInt(p.trim(), 10))
.filter((p) => Number.isInteger(p) && p > 0);
}
const RESERVED_PORTS = new Set([4040, ...parsePortList(process.env.FUSION_RESERVED_PORTS)]);
/*
* FNXC:BootSmoke 2026-07-07-00:00:
* On macOS the just-terminated `fn serve` child (plus OS-level fsevents/Spotlight
* indexing) can still be writing into the throwaway `$HOME`/project dirs
* (`/var/folders/.../fusion-boot-smoke-*`) when cleanup runs, so a synchronous
* `rmSync(..., { recursive: true, force: true })` intermittently throws ENOTEMPTY.
* Cleanup runs from the `process.on("exit")` handler and the retry-port branch —
* both AFTER `boot-smoke: PASS` has already been decided/printed — so an uncaught
* throw there turned a genuine pass into a `pnpm verify:fast` failure. `rmSync`'s
* own `maxRetries`/`retryDelay` already retries transient ENOTEMPTY/EBUSY/EPERM
* synchronously (exit handlers cannot await, so async `fs.rm` is not an option
* here); the outer try/catch is the final safety net that swallows the error if
* removal never succeeds, so a post-PASS cleanup failure can never fail the gate.
*/
/**
* Remove a throwaway boot-smoke temp dir, tolerating the macOS ENOTEMPTY
* async-writer race. Never throws — a cleanup failure after the smoke
* verdict is already decided must not change the exit code.
*/
export function removeTempDir(dir, { rm = rmSync, maxRetries = 5, retryDelayMs = 100 } = {}) {
try {
rm(dir, { recursive: true, force: true, maxRetries, retryDelay: retryDelayMs });
} catch (err) {
console.warn(`boot-smoke: cleanup of ${dir} failed after retries (ignored): ${err?.message ?? err}`);
}
}
/** Ask the OS for a free ephemeral port, retrying if it lands on a reserved one. */
async function getEphemeralPort() {
for (let attempt = 0; attempt < 10; attempt++) {
const port = await new Promise((resolve, reject) => {
const srv = createServer();
srv.once("error", reject);
srv.listen(0, "127.0.0.1", () => {
const { port } = srv.address();
srv.close(() => resolve(port));
});
});
if (!RESERVED_PORTS.has(port)) return port;
}
throw new Error("could not obtain a non-reserved ephemeral port");
}
function fail(message, stderr = "") {
console.error(`boot-smoke: FAIL — ${message}`);
if (stderr.trim()) {
console.error("--- child stderr (tail) ---");
console.error(stderr.split("\n").slice(-40).join("\n"));
}
process.exit(1);
}
async function pollHealth(port, deadline) {
const url = `http://127.0.0.1:${port}/api/health`;
let lastError = "no response";
while (Date.now() < deadline) {
const controller = new AbortController();
const abortTimer = setTimeout(() => controller.abort(), 2_000);
try {
const res = await fetch(url, { signal: controller.signal });
if (res.status === 200) return;
lastError = `HTTP ${res.status}`;
} catch (err) {
lastError = err?.cause?.code ?? err?.name ?? String(err);
} finally {
clearTimeout(abortTimer);
}
await new Promise((r) => setTimeout(r, 500));
}
throw new Error(`health check never returned 200 (last: ${lastError})`);
}
async function main() {
// 1. CLI answers --help.
const help = spawnSync(process.execPath, [cliBin, "--help"], {
encoding: "utf8",
timeout: 30_000,
});
if (help.status !== 0) {
fail(`\`fn --help\` exited ${help.status ?? `signal ${help.signal}`}`, help.stderr ?? "");
}
if (!/serve/i.test(help.stdout ?? "")) {
fail("`fn --help` output does not mention the serve command", help.stderr ?? "");
}
console.log("boot-smoke: `fn --help` OK");
// 2. Real server boot on an ephemeral port with isolated HOME/project state.
// The ephemeral-port probe is inherently TOCTOU (probe closes before the
// server binds), so an EADDRINUSE loss on a busy machine retries with a
// fresh port instead of failing the gate.
let cleanup = () => {};
process.on("exit", () => cleanup());
// Node does NOT fire 'exit' on signals by default. A cancelled CI job
// (timeout, manual cancel, runner eviction) sends SIGTERM — without these
// handlers the serve child would be orphaned.
for (const sig of ["SIGTERM", "SIGINT"]) {
process.on(sig, () => {
cleanup();
process.exit(sig === "SIGINT" ? 130 : 143);
});
}
for (let attempt = 1; attempt <= BOOT_ATTEMPTS; attempt++) {
const result = await bootAndVerify(attempt, (fn) => (cleanup = fn));
if (result === "retry-port") continue;
console.log("boot-smoke: PASS");
return;
}
fail(`could not bind a server port after ${BOOT_ATTEMPTS} attempts (EADDRINUSE each time)`);
}
/**
* One boot attempt: spawn, poll health, verify SIGTERM shutdown.
* Returns "retry-port" when the child lost the ephemeral-port race
* (EADDRINUSE); calls fail() (which exits) on any real failure.
*/
async function bootAndVerify(attempt, registerCleanup) {
const port = await getEphemeralPort();
const isolatedHome = mkdtempSync(path.join(tmpdir(), "fusion-boot-smoke-home-"));
const isolatedProject = mkdtempSync(path.join(tmpdir(), "fusion-boot-smoke-project-"));
let stderrBuf = "";
const child = spawn(
process.execPath,
[
cliBin,
"serve",
"--port",
String(port),
"--host",
"127.0.0.1",
// FNXC:BootSmoke 2026-06-19-12:36: The boot smoke verifies HTTP startup, not autonomous task execution. Run against an isolated throwaway project and use --paused so a developer worktree with an in-progress task or missing task-local artifacts cannot make the merge gate fail before /api/health serves.
"--paused",
],
{
cwd: isolatedProject,
env: {
...process.env,
HOME: isolatedHome,
FUSION_SKIP_ONBOARDING: "1",
// FNXC:BackendFlip 2026-06-26-14:55:
// Force the smoke to exercise the embedded PostgreSQL backend. Unset
// DATABASE_URL so a developer's external DB connection never leaks in
// (the smoke must prove the zero-config embedded path boots). Unset
// FUSION_NO_EMBEDDED_PG so the smoke cannot be opted out by an
// inherited env var — the embedded default is what the gate must prove.
DATABASE_URL: undefined,
FUSION_NO_EMBEDDED_PG: undefined,
// Make sure nothing inherits a PORT that fights the explicit flag.
PORT: undefined,
},
stdio: ["ignore", "pipe", "pipe"],
},
);
child.stderr.on("data", (d) => (stderrBuf += d));
child.stdout.on("data", (d) => (stderrBuf += d));
registerCleanup(() => {
// 'exit' handlers cannot await: escalate straight to SIGKILL so a child
// that ignores SIGTERM is never orphaned holding the port/tmpdir. The
// graceful SIGTERM path below runs before this on the success path.
try {
if (child.exitCode === null && !child.killed) child.kill("SIGKILL");
} catch {
// ESRCH: child already reaped between the check and the kill — fine.
}
removeTempDir(isolatedHome);
removeTempDir(isolatedProject);
});
const exitedEarly = new Promise((resolve) => {
child.once("exit", (code, signal) => resolve({ code, signal }));
});
try {
await Promise.race([
pollHealth(port, Date.now() + HEALTH_TIMEOUT_MS),
exitedEarly.then(({ code, signal }) => {
throw new Error(`server exited before becoming healthy (${code ?? `signal ${signal}`})`);
}),
]);
} catch (err) {
if (/EADDRINUSE/.test(stderrBuf) && attempt < BOOT_ATTEMPTS) {
console.log(`boot-smoke: port :${port} lost to another process (EADDRINUSE), retrying with a fresh port (attempt ${attempt}/${BOOT_ATTEMPTS})`);
await exitedEarly; // child is already dead or dying; wait so cleanup is race-free
removeTempDir(isolatedHome);
removeTempDir(isolatedProject);
return "retry-port";
}
fail(err.message, stderrBuf);
}
console.log(`boot-smoke: GET /api/health 200 on :${port}`);
// 3. Clean shutdown of OUR child only. The verdict requires BOTH that
// SIGTERM was actually delivered (a server that died between the health
// check and here is a failure, not a pass) AND that the exit was clean
// (SIGTERM or exit code 0) — a crash after serving is a broken boot path.
let sigtermSent = false;
try {
sigtermSent = child.kill("SIGTERM");
} catch {
// ESRCH: server already exited — sigtermSent stays false and fails below.
}
const { code, signal } = await Promise.race([
exitedEarly,
new Promise((resolve) =>
setTimeout(() => resolve({ code: null, signal: "timeout" }), SHUTDOWN_TIMEOUT_MS),
),
]);
if (!sigtermSent) {
fail(`server exited on its own after the health check (${code ?? `signal ${signal}`}) — SIGTERM shutdown could not be verified`, stderrBuf);
}
if (signal === "timeout") {
child.kill("SIGKILL");
fail("server did not shut down within 15s of SIGTERM", stderrBuf);
}
if (signal !== "SIGTERM" && code !== 0) {
fail(`server exited uncleanly on SIGTERM (${code ?? `signal ${signal}`})`, stderrBuf);
}
console.log(`boot-smoke: clean shutdown (${code ?? signal})`);
return "ok";
}
// FNXC:BootSmoke 2026-07-07-00:00: Guard the top-level boot so importing this
// module (e.g. from the regression test to reach `removeTempDir`) never spawns
// a real server; only a direct `node scripts/boot-smoke.mjs` invocation runs it.
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
main().catch((err) => fail(err.message ?? String(err)));
}