Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Preserve exact SQL signatures during catalog backup restore

[._.]/ Adam Eivyf335ba890738
diff --git a/server/routes/catalogParsedBodies.test.js b/server/routes/catalogParsedBodies.test.js
index 9065873ef9..658f205afc 100644
--- a/server/routes/catalogParsedBodies.test.js
+++ b/server/routes/catalogParsedBodies.test.js
@@ -14,6 +14,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';
const mocks = vi.hoisted(() => ({
createIngredient: vi.fn(),
getIngredient: vi.fn(),
+ getIngredientIdentityIds: vi.fn(),
getIngredientRevision: vi.fn(),
listRefsForIngredient: vi.fn(),
updateIngredient: vi.fn(),
@@ -30,6 +31,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('../services/catalogDB.js', () => ({
createIngredient: mocks.createIngredient,
getIngredient: mocks.getIngredient,
+ getIngredientIdentityIds: mocks.getIngredientIdentityIds,
getIngredientRevision: mocks.getIngredientRevision,
listRefsForIngredient: mocks.listRefsForIngredient,
updateIngredient: mocks.updateIngredient,
@@ -60,6 +62,7 @@ beforeEach(() => {
vi.clearAllMocks();
mocks.createIngredient.mockImplementation(async (body) => ({ id: 'ing-1', ...body }));
mocks.getIngredient.mockResolvedValue({ id: 'ing-1', name: 'Before', payload: {} });
+ mocks.getIngredientIdentityIds.mockImplementation(async id => [id]);
mocks.getIngredientRevision.mockResolvedValue(null);
mocks.listRefsForIngredient.mockResolvedValue([]);
mocks.updateIngredient.mockImplementation(async (id, patch) => ({ id, ...patch }));
@@ -194,6 +197,7 @@ describe('Catalog parsed write bodies', () => {
snapshot('user');
return ingredient;
});
+ mocks.getIngredient.mockImplementation(async () => ingredient);
mocks.linkIngredientToRef.mockImplementation(async () => {
canon.characters = [{
id: 'canon-1', ingredientId: ingredient.id, name: ingredient.name,
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
index 7d8a8a4614..883a9f7b87 100644
--- a/server/services/backup.db.test.js
+++ b/server/services/backup.db.test.js
@@ -291,6 +291,29 @@ describe.skipIf(!ready)('restore older database schema', () => {
expect((await query('SELECT 1 FROM writers_room_folders WHERE id = $1', [folderId])).rowCount).toBe(1);
});
+ it('refuses unknown functions and wrong overloads even when a shipped function is absent', async () => {
+ // Missing signatures resolve to NULL: they must not admit an unrelated
+ // function through nullable NOT IN comparisons during an older restore.
+ await query('DROP FUNCTION public.catalog_resolve_ingredient_id(text) RESTRICT');
+ try {
+ for (const signature of ['unexpected_restore_function()', 'catalog_resolve_ingredient_id(integer)']) {
+ await query(`CREATE FUNCTION public.${signature} RETURNS text LANGUAGE SQL AS $$ SELECT 'unapproved'::text $$`);
+ try {
+ const before = (await query('SELECT tableoid, xmin, name FROM tribe_people WHERE id = $1', [personId])).rows;
+ for (const dryRun of [true, false]) {
+ expect(await restore(dryRun)).toMatchObject({ status: 'failed', reason: 'restore_preflight' });
+ }
+ expect((await query('SELECT tableoid, xmin, name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual(before);
+ expect((await query('SELECT to_regprocedure($1) IS NOT NULL AS present', [`public.${signature}`])).rows[0].present).toBe(true);
+ } finally {
+ await query(`DROP FUNCTION IF EXISTS public.${signature} RESTRICT`);
+ }
+ }
+ } finally {
+ await ensureSchema({ force: true });
+ }
+ });
+
it('preflights unknown objects and external dependencies without mutations, including preview', async () => {
await query('CREATE TABLE public.unexpected_restore_record (id integer PRIMARY KEY)');
await query('INSERT INTO public.unexpected_restore_record VALUES (42)');
diff --git a/server/services/backupDatabaseReset.js b/server/services/backupDatabaseReset.js
index e2be72a709..b14a093b9d 100644
--- a/server/services/backupDatabaseReset.js
+++ b/server/services/backupDatabaseReset.js
@@ -12,7 +12,11 @@ export async function getDatabaseResetPlan() {
// the live database. Fail closed on objects not declared by this version.
const names = (pattern) => [...new Set([...ddl.matchAll(pattern)].map(match => match[1]))];
const tables = names(/CREATE TABLE IF NOT EXISTS ([a-z_][a-z_0-9]*)/g);
- const functions = names(/CREATE OR REPLACE FUNCTION ([a-z_][a-z_0-9]*)\(\)/g);
+ // Recognize only the signatures currently shipped by the schema: trigger
+ // functions without arguments and the catalog resolver's named TEXT input.
+ // Unsupported future declarations remain excluded and fail preflight closed.
+ const functions = names(/CREATE OR REPLACE FUNCTION ([a-z_][a-z_0-9]*\((?:[a-z_][a-z_0-9]* TEXT)?\))/g)
+ .map(signature => `public.${signature.replace(/\([a-z_][a-z_0-9]* TEXT\)/, '(text)')}`);
const sequences = names(/CREATE SEQUENCE IF NOT EXISTS ([a-z_][a-z_0-9]*)/g);
const literals = values => values.map(value => `'${value}'`).join(', ');
const preflight = `DO $portos_restore$
@@ -45,7 +49,8 @@ export async function getDatabaseResetPlan() {
WHERE n.nspname = 'public'
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass
AND d.objid = p.oid AND d.deptype = 'e')
- AND (p.proname NOT IN (${literals(functions)}) OR p.pronargs <> 0
+ AND (NOT EXISTS (SELECT 1 FROM unnest(ARRAY[${literals(functions)}]) AS allowed(signature)
+ WHERE p.oid = to_regprocedure(allowed.signature))
OR p.proowner <> (SELECT oid FROM pg_roles WHERE rolname = current_user))
) THEN RAISE EXCEPTION 'Restore preflight: unexpected application-schema function or owner'; END IF;
@@ -85,7 +90,7 @@ export async function getDatabaseResetPlan() {
// including changes between preflight and replay. Never use CASCADE here.
const reset = `${preflight}
DROP TABLE IF EXISTS ${tables.map(name => `public.${name}`).join(', ')} RESTRICT;
- DROP FUNCTION IF EXISTS ${functions.map(name => `public.${name}()`).join(', ')} RESTRICT;
+ DROP FUNCTION IF EXISTS ${functions.join(', ')} RESTRICT;
DROP SEQUENCE IF EXISTS ${sequences.map(name => `public.${name}`).join(', ')} RESTRICT;
CREATE SCHEMA IF NOT EXISTS public;
CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA public;