|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect, afterAll } from 'vitest'; |
| 4 | +import { spawnSync } from 'node:child_process'; |
| 5 | +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 6 | +import { tmpdir } from 'node:os'; |
| 7 | +import { dirname, join, resolve } from 'node:path'; |
| 8 | +import { fileURLToPath } from 'node:url'; |
| 9 | +import Database from 'better-sqlite3'; |
| 10 | + |
| 11 | +/** |
| 12 | + * [#22579] `os migrate plan` / `apply` plan every object against the database |
| 13 | + * it lives in — a lifecycle-classed one in the `telemetry` sibling a serving |
| 14 | + * boot keeps it in (ADR-0057 §3.6), never in the primary. |
| 15 | + * |
| 16 | + * ## The defect, measured on `main` `d8830c2805` |
| 17 | + * |
| 18 | + * A development `os serve` boot of an app declaring `requires: ['auth', |
| 19 | + * 'automation']` keeps nine objects in `boot.telemetry.db`: `sys_activity`, |
| 20 | + * `sys_audit_log`, `sys_automation_run`, `sys_flow_dispatch`, |
| 21 | + * `sys_http_delivery`, `sys_job_run`, `sys_metadata_audit`, `sys_notification` |
| 22 | + * and `sys_notification_delivery`. The one-shot migration boot never |
| 23 | + * provisioned that sibling, so every one of them resolved to the primary: |
| 24 | + * `plan` listed all nine as `create_table`, and `apply --yes` created all nine |
| 25 | + * in `boot.db` — empty orphans beside the tables the served boot uses. |
| 26 | + * |
| 27 | + * ## What is pinned |
| 28 | + * |
| 29 | + * - after a development boot, the plan names the sibling, lists no |
| 30 | + * lifecycle-classed object for the primary, and examines both databases' |
| 31 | + * objects; `apply` creates nothing, and neither database moves; |
| 32 | + * - the CONTROL: a deployment with no sibling (`OS_TELEMETRY_DB=0`) plans as |
| 33 | + * it always did — no sibling named, nothing pending; |
| 34 | + * - a plan with the sibling on over a deployment that has none yet plans the |
| 35 | + * lifecycle-classed objects into it, and brings no file into existence (the |
| 36 | + * read-only probe, #6743, holds for the sibling as for the primary). |
| 37 | + * |
| 38 | + * Each step runs through the public door — `serve`'s provision-and-exit |
| 39 | + * (`OS_MIGRATE_AND_EXIT=1`), then the commands — from the source entry, which |
| 40 | + * pins `NODE_ENV=development`: a development boot on both sides, as `os dev` |
| 41 | + * followed by `os migrate plan` in that environment is. |
| 42 | + */ |
| 43 | + |
| 44 | +const HERE = dirname(fileURLToPath(import.meta.url)); |
| 45 | +const CLI_ROOT = resolve(HERE, '..', '..', '..'); |
| 46 | +const RUN_DEV = resolve(CLI_ROOT, 'bin', 'run-dev.js'); |
| 47 | +const TSX = resolve(CLI_ROOT, '..', '..', 'node_modules', '.bin', 'tsx'); |
| 48 | +const CASE_TIMEOUT_MS = 300_000; |
| 49 | + |
| 50 | +/** The one table outside the object set (`PackageServicePlugin.start()`'s raw DDL; see the boot-parity pin). */ |
| 51 | +const NOT_AN_OBJECT = ['sys_packages']; |
| 52 | + |
| 53 | +const CONFIG = [ |
| 54 | + 'export default {', |
| 55 | + " manifest: { id: 'com.example.os22579sibling', name: 'sibling', version: '0.0.0', type: 'app' },", |
| 56 | + " requires: ['auth', 'automation'],", |
| 57 | + " objects: [{ name: 'os22579_sibling_app', fields: { title: { type: 'text' } } }],", |
| 58 | + '};', |
| 59 | + '', |
| 60 | +].join('\n'); |
| 61 | + |
| 62 | +const dirs: string[] = []; |
| 63 | +afterAll(() => { |
| 64 | + for (const d of dirs) { |
| 65 | + try { rmSync(d, { recursive: true, force: true }); } catch { /* best-effort */ } |
| 66 | + } |
| 67 | +}); |
| 68 | + |
| 69 | +interface Fixture { |
| 70 | + dir: string; |
| 71 | + primary: string; |
| 72 | + sibling: string; |
| 73 | +} |
| 74 | + |
| 75 | +function fixture(): Fixture { |
| 76 | + const dir = mkdtempSync(join(tmpdir(), 'os-22579-sibling-')); |
| 77 | + dirs.push(dir); |
| 78 | + mkdirSync(join(dir, 'dist'), { recursive: true }); |
| 79 | + writeFileSync(join(dir, 'objectstack.config.ts'), CONFIG); |
| 80 | + // `resolveTelemetryDbPath`'s dev default: `<primary>.telemetry.<ext>`. |
| 81 | + return { dir, primary: join(dir, 'boot.db'), sibling: join(dir, 'boot.telemetry.db') }; |
| 82 | +} |
| 83 | + |
| 84 | +/** The child's environment: the fixture's database, nothing inherited that retargets it or the sibling. */ |
| 85 | +function childEnv(f: Fixture, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { |
| 86 | + const env: NodeJS.ProcessEnv = { ...process.env }; |
| 87 | + for (const key of [ |
| 88 | + 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', |
| 89 | + 'OS_TELEMETRY_DB', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', |
| 90 | + ]) { |
| 91 | + delete env[key]; |
| 92 | + } |
| 93 | + return { |
| 94 | + ...env, |
| 95 | + OS_DATABASE_URL: `file:${f.primary}`, |
| 96 | + OS_ARTIFACT_PATH: join(f.dir, 'dist', 'objectstack.json'), |
| 97 | + OS_CLOUD_URL: 'off', |
| 98 | + OS_TELEMETRY_DISABLED: '1', |
| 99 | + OS_AUTH_SECRET: 'os22579-sibling-secret-at-least-32-characters', |
| 100 | + OS_LOG_LEVEL: 'warn', |
| 101 | + ...extra, |
| 102 | + }; |
| 103 | +} |
| 104 | + |
| 105 | +/** `os serve`'s own provision-and-exit: the full composition schema-synced into the fixture's database(s). */ |
| 106 | +function serveBoot(f: Fixture, extra: NodeJS.ProcessEnv = {}): void { |
| 107 | + const boot = spawnSync(TSX, [RUN_DEV, 'serve', '--no-server', '--no-ui', '--no-console', '--port', '0'], { |
| 108 | + cwd: f.dir, env: childEnv(f, { ...extra, OS_MIGRATE_AND_EXIT: '1' }), encoding: 'utf8', timeout: 240_000, |
| 109 | + }); |
| 110 | + expect(boot.status, `the serving boot did not provision the database:\n${`${boot.stdout}\n${boot.stderr}`.slice(-800)}`) |
| 111 | + .toBe(0); |
| 112 | +} |
| 113 | + |
| 114 | +function command(f: Fixture, argv: string[], extra: NodeJS.ProcessEnv = {}): { exit: number | null; payload: any } { |
| 115 | + const run = spawnSync(TSX, [RUN_DEV, 'migrate', ...argv], { cwd: f.dir, env: childEnv(f, extra), encoding: 'utf8', timeout: 240_000 }); |
| 116 | + let payload: any; |
| 117 | + try { payload = JSON.parse(run.stdout); } catch { payload = { unparsed: `${run.stdout}\n${run.stderr}`.slice(-800) }; } |
| 118 | + return { exit: run.status, payload }; |
| 119 | +} |
| 120 | + |
| 121 | +/** A database's tables, a rotation shard read as its object. */ |
| 122 | +function tables(file: string): string[] { |
| 123 | + const db = new Database(file, { readonly: true }); |
| 124 | + try { |
| 125 | + const names = (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all() as Array<{ name: string }>) |
| 126 | + .map((t) => t.name.replace(/__r\d{6,8}$/, '')); |
| 127 | + return [...new Set(names)].sort(); |
| 128 | + } finally { |
| 129 | + db.close(); |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +/** The schema and every row of every table — what "the database did not move" is read against. */ |
| 134 | +function state(file: string): unknown { |
| 135 | + const db = new Database(file, { readonly: true }); |
| 136 | + try { |
| 137 | + const schema = db.prepare('SELECT type, name, sql FROM sqlite_master ORDER BY type, name').all() as Array<{ type: string; name: string }>; |
| 138 | + const rows: Record<string, unknown> = {}; |
| 139 | + for (const entry of schema) { |
| 140 | + if (entry.type !== 'table' || entry.name.startsWith('sqlite_')) continue; |
| 141 | + rows[entry.name] = db.prepare(`SELECT * FROM "${entry.name}" ORDER BY rowid`).all(); |
| 142 | + } |
| 143 | + return { schema, rows }; |
| 144 | + } finally { |
| 145 | + db.close(); |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +const pendingTables = (payload: any): string[] => (payload.pending ?? []).map((p: any) => `${p.kind}:${p.table}`).sort(); |
| 150 | + |
| 151 | +describe('os migrate plan / apply plan each object against the database it lives in (#22579)', () => { |
| 152 | + it('after a development boot: the sibling is named and planned, nothing lifecycle-classed is planned for the primary, apply creates nothing', () => { |
| 153 | + const f = fixture(); |
| 154 | + serveBoot(f); |
| 155 | + |
| 156 | + // The serving boot's layout — the thing the plan must describe. |
| 157 | + expect(existsSync(f.sibling), 'the development boot provisioned no telemetry sibling: nothing to plan against').toBe(true); |
| 158 | + const primaryTables = tables(f.primary); |
| 159 | + const siblingTables = tables(f.sibling); |
| 160 | + expect(siblingTables).toEqual(expect.arrayContaining(['sys_audit_log', 'sys_metadata_audit'])); |
| 161 | + expect(primaryTables.filter((t) => siblingTables.includes(t)), 'one table in both databases').toEqual([]); |
| 162 | + const before = { primary: state(f.primary), sibling: state(f.sibling) }; |
| 163 | + |
| 164 | + const plan = command(f, ['plan', '--json']); |
| 165 | + expect(plan.exit, JSON.stringify(plan.payload).slice(0, 800)).toBe(0); |
| 166 | + // Nothing to create anywhere — above all no lifecycle-classed object for the primary. |
| 167 | + expect(pendingTables(plan.payload)).toEqual([]); |
| 168 | + expect(plan.payload.changes).toEqual([]); |
| 169 | + expect(plan.payload.telemetryDatabase).toBe(f.sibling); |
| 170 | + expect(plan.payload.composition?.coverage?.unexaminedObjects).toBe(0); |
| 171 | + // Both databases' objects examined: their tables, less the raw-DDL one. |
| 172 | + expect(plan.payload.managedTables).toBe(primaryTables.length - NOT_AN_OBJECT.length + siblingTables.length); |
| 173 | + // A plan writes nothing, to either database. |
| 174 | + expect({ primary: state(f.primary), sibling: state(f.sibling) }).toEqual(before); |
| 175 | + |
| 176 | + const apply = command(f, ['apply', '--yes', '--json']); |
| 177 | + expect(apply.exit, JSON.stringify(apply.payload).slice(0, 800)).toBe(0); |
| 178 | + expect(apply.payload.created).toEqual([]); |
| 179 | + expect(apply.payload.applied).toEqual([]); |
| 180 | + expect(apply.payload.telemetryDatabase).toBe(f.sibling); |
| 181 | + // No orphan in the primary, and nothing moved in either database. |
| 182 | + expect(tables(f.primary)).toEqual(primaryTables); |
| 183 | + expect({ primary: state(f.primary), sibling: state(f.sibling) }).toEqual(before); |
| 184 | + }, CASE_TIMEOUT_MS); |
| 185 | + |
| 186 | + it('the control — a deployment with no sibling plans as it did; with the sibling on, an absent one is planned and not created', () => { |
| 187 | + const f = fixture(); |
| 188 | + serveBoot(f, { OS_TELEMETRY_DB: '0' }); |
| 189 | + expect(existsSync(f.sibling)).toBe(false); |
| 190 | + const primaryTables = tables(f.primary); |
| 191 | + expect(primaryTables).toEqual(expect.arrayContaining(['sys_audit_log', 'sys_metadata_audit'])); |
| 192 | + |
| 193 | + // No sibling: no sibling named, nothing pending, every object on the primary. |
| 194 | + const control = command(f, ['plan', '--json'], { OS_TELEMETRY_DB: '0' }); |
| 195 | + expect(control.exit, JSON.stringify(control.payload).slice(0, 800)).toBe(0); |
| 196 | + expect('telemetryDatabase' in control.payload).toBe(false); |
| 197 | + expect(pendingTables(control.payload)).toEqual([]); |
| 198 | + expect(control.payload.changes).toEqual([]); |
| 199 | + expect(control.payload.managedTables).toBe(primaryTables.length - NOT_AN_OBJECT.length); |
| 200 | + |
| 201 | + // The sibling on, over this deployment: the serving boot would now keep |
| 202 | + // the lifecycle-classed objects in a sibling that does not exist yet, so |
| 203 | + // the plan creates them there — and, being a dry run, creates no file. |
| 204 | + const before = state(f.primary); |
| 205 | + const plan = command(f, ['plan', '--json']); |
| 206 | + expect(plan.exit, JSON.stringify(plan.payload).slice(0, 800)).toBe(0); |
| 207 | + const pending = pendingTables(plan.payload); |
| 208 | + expect(pending).toEqual(expect.arrayContaining(['create_table:sys_audit_log', 'create_table:sys_metadata_audit'])); |
| 209 | + expect(pending.every((p) => p.startsWith('create_table:')), pending.join(', ')).toBe(true); |
| 210 | + expect(plan.payload.telemetryDatabase).toBe(f.sibling); |
| 211 | + expect(existsSync(f.sibling), 'a dry run brought the telemetry sibling into existence').toBe(false); |
| 212 | + expect(state(f.primary)).toEqual(before); |
| 213 | + }, CASE_TIMEOUT_MS); |
| 214 | +}); |
0 commit comments