7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(custom): keep user-deleted custom models deleted across scheduled sync (#926) (#931)
suantea (asuan_suan)ee849ed63570
diff --git a/server/src/__tests__/db/migrate/custom-model-tombstones.test.ts b/server/src/__tests__/db/migrate/custom-model-tombstones.test.tsnew file mode 100644index 00000000..42276e7d--- /dev/null+++ b/server/src/__tests__/db/migrate/custom-model-tombstones.test.ts@@ -0,0 +1,63 @@+import Database from 'better-sqlite3';+import { afterEach, describe, expect, it } from 'vitest';+import { up, down } from '../../../db/migrations/20260819_000001_custom_model_tombstones.js';++function makeDb(): Database.Database {+ const db = new Database(':memory:');+ db.exec(`+ CREATE TABLE models (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ platform TEXT NOT NULL,+ model_id TEXT NOT NULL,+ endpoint_scope TEXT NOT NULL DEFAULT ''+ );+ `);+ db.prepare("INSERT INTO models (platform, model_id, endpoint_scope) VALUES ('custom', 'model-a', 'http://relay:9999')").run();+ return db;+}++const dbs: Database.Database[] = [];+afterEach(() => {+ for (const db of dbs.splice(0)) db.close();+});++describe('custom_model_tombstones migration (#926)', () => {+ it('creates the tombstone table keyed by (endpoint_scope, model_id)', () => {+ const db = makeDb();+ dbs.push(db);+ up(db);++ const cols = (db.prepare('PRAGMA table_info(custom_model_tombstones)').all() as { name: string }[])+ .map(c => c.name);+ expect(cols).toContain('endpoint_scope');+ expect(cols).toContain('model_id');+ expect(cols).toContain('created_at');++ db.prepare(+ 'INSERT INTO custom_model_tombstones (endpoint_scope, model_id) VALUES (?, ?)',+ ).run('http://relay:9999', 'model-a');+ // The primary key rejects a duplicate for the same endpoint+model.+ expect(() =>+ db.prepare(+ 'INSERT INTO custom_model_tombstones (endpoint_scope, model_id) VALUES (?, ?)',+ ).run('http://relay:9999', 'model-a'),+ ).toThrow();+ });++ it('down drops the table and leaves existing data intact', () => {+ const db = makeDb();+ dbs.push(db);+ up(db);+ db.prepare(+ 'INSERT INTO custom_model_tombstones (endpoint_scope, model_id) VALUES (?, ?)',+ ).run('http://relay:9999', 'model-a');+ down(db);++ const tables = (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { name: string }[])+ .map(t => t.name);+ expect(tables).not.toContain('custom_model_tombstones');+ // The models table (and its data) survives a revert.+ const models = db.prepare('SELECT COUNT(*) AS n FROM models').get() as { n: number };+ expect(models.n).toBe(1);+ });+});diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex acb3f9d5..1534d539 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -27,6 +27,7 @@ const KEY_MODEL_SCOPE_FILENAME = '20260805_000001_key_model_scope.ts';const CLIENT_PROFILES_FILENAME = '20260805_000002_client_profiles.ts';const API_KEY_PROXY_FILENAME = '20260810_000001_api_key_proxy.ts';const PLAYGROUND_CONVERSATIONS_FILENAME = '20260820_000001_playground_conversations.ts';+const CUSTOM_MODEL_TOMBSTONES_FILENAME = '20260819_000001_custom_model_tombstones.ts';interface SchemaRow {type: string;@@ -99,6 +100,7 @@ describe('migration round trip', () => {KEY_MODEL_SCOPE_FILENAME,CLIENT_PROFILES_FILENAME,API_KEY_PROXY_FILENAME,+ CUSTOM_MODEL_TOMBSTONES_FILENAME,PLAYGROUND_CONVERSATIONS_FILENAME,]);} finally {diff --git a/server/src/__tests__/services/custom-model-sync.test.ts b/server/src/__tests__/services/custom-model-sync.test.tsindex 8f6fa97a..e83e2d43 100644--- a/server/src/__tests__/services/custom-model-sync.test.ts+++ b/server/src/__tests__/services/custom-model-sync.test.ts@@ -2,6 +2,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { getDb, initDb } from '../../db/index.js';import { runCustomModelSync, customModelSyncIntervalMs, customModelSyncFreePatterns, startCustomModelSync } from '../../services/custom-model-sync.js';import { discoverEndpointModels } from '../../services/model-discovery.js';+import { registerCustomModels } from '../../services/custom-model-register.js';+import { recordCustomModelTombstone } from '../../services/custom-model-tombstone.js';import { endpointScopeForBaseUrl } from '../../lib/endpoint-scope.js';// The sync pass talks to the outside world ONLY through discoverEndpointModels;@@ -186,4 +188,62 @@ describe('custom model sync', () => {if (prev === undefined) delete process.env.CUSTOM_MODEL_SYNC_FREE_PATTERNS;else process.env.CUSTOM_MODEL_SYNC_FREE_PATTERNS = prev;});++ it('does not resurrect a model the operator deleted (tombstoned)', async () => {+ addCustomEndpoint('http://localhost:9999');+ const scope = endpointScopeForBaseUrl('http://localhost:9999');+ // The operator deleted this model from the list; the tombstone records that.+ recordCustomModelTombstone(getDb(), scope, 'model-a');+ (discoverEndpointModels as unknown as ReturnType<typeof vi.fn>).mockResolvedValue([+ { id: 'model-a', ownedBy: null },+ { id: 'model-b', ownedBy: null },+ ]);++ const result = await runCustomModelSync(getDb());++ expect(result.tombstoned).toBe(1);+ expect(result.added).toBe(1);+ expect(customModelIds()).toEqual(['model-b']);+ });++ it('keeps the tombstone scoped: a deletion on one relay never hides the same id on another', async () => {+ addCustomEndpoint('http://relay-a:9999');+ addCustomEndpoint('http://relay-b:9999');+ recordCustomModelTombstone(getDb(), endpointScopeForBaseUrl('http://relay-a:9999'), 'shared-model');+ (discoverEndpointModels as unknown as ReturnType<typeof vi.fn>).mockResolvedValue([+ { id: 'shared-model', ownedBy: null },+ ]);++ const result = await runCustomModelSync(getDb());++ expect(result.tombstoned).toBe(1);+ expect(result.added).toBe(1);+ // relay-b still registered its copy: only relay-a's deletion is honored.+ const rows = getDb().prepare(+ "SELECT model_id, endpoint_scope FROM models WHERE platform = 'custom' AND model_id = 'shared-model'",+ ).all() as { model_id: string; endpoint_scope: string }[];+ expect(rows).toEqual([{ model_id: 'shared-model', endpoint_scope: endpointScopeForBaseUrl('http://relay-b:9999') }]);+ });++ it('an explicit re-registration clears the tombstone so the next sync can add it again', async () => {+ addCustomEndpoint('http://localhost:9999');+ const scope = endpointScopeForBaseUrl('http://localhost:9999');+ recordCustomModelTombstone(getDb(), scope, 'model-a');+ // Operator changes their mind and explicitly re-adds the model.+ registerCustomModels(getDb(), 'http://localhost:9999', undefined, 'endpoint', undefined, [+ { modelId: 'model-a', displayName: null },+ ]);++ (discoverEndpointModels as unknown as ReturnType<typeof vi.fn>).mockResolvedValue([+ { id: 'model-a', ownedBy: null },+ ]);++ const result = await runCustomModelSync(getDb());++ // Tombstone is gone: model-a is already registered again, so the pass just+ // sees an existing row (skipped), never a tombstoned one.+ expect(result.tombstoned).toBe(0);+ expect(result.skipped).toBe(1);+ expect(customModelIds()).toEqual(['model-a']);+ });});diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex 98e1e9d2..3c05fae1 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -22,6 +22,7 @@ import * as keyModelScope from '../migrations/20260805_000001_key_model_scope.jsimport * as clientProfiles from '../migrations/20260805_000002_client_profiles.js';import * as apiKeyProxy from '../migrations/20260810_000001_api_key_proxy.js';import * as playgroundConversations from '../migrations/20260820_000001_playground_conversations.js';+import * as customModelTombstones from '../migrations/20260819_000001_custom_model_tombstones.js';export interface MigrationModule {up(db: Db): void;@@ -56,6 +57,7 @@ export const KEY_MODEL_SCOPE_FILENAME = '20260805_000001_key_model_scope.ts';export const CLIENT_PROFILES_FILENAME = '20260805_000002_client_profiles.ts';export const API_KEY_PROXY_FILENAME = '20260810_000001_api_key_proxy.ts';export const PLAYGROUND_CONVERSATIONS_FILENAME = '20260820_000001_playground_conversations.ts';+export const CUSTOM_MODEL_TOMBSTONES_FILENAME = '20260819_000001_custom_model_tombstones.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -80,5 +82,6 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: KEY_MODEL_SCOPE_FILENAME, module: keyModelScope },{ filename: CLIENT_PROFILES_FILENAME, module: clientProfiles },{ filename: API_KEY_PROXY_FILENAME, module: apiKeyProxy },+ { filename: CUSTOM_MODEL_TOMBSTONES_FILENAME, module: customModelTombstones },{ filename: PLAYGROUND_CONVERSATIONS_FILENAME, module: playgroundConversations },];diff --git a/server/src/db/migrations/20260819_000001_custom_model_tombstones.ts b/server/src/db/migrations/20260819_000001_custom_model_tombstones.tsnew file mode 100644index 00000000..4d9af690--- /dev/null+++ b/server/src/db/migrations/20260819_000001_custom_model_tombstones.ts@@ -0,0 +1,22 @@+// Migration: keep user-deleted custom models deleted across the scheduled sync+// Created: 2026-08-19+//+// DOWN: reversible — the added table is dropped, which simply means deleted+// custom models can be re-added by the next sync pass again (#926).++import type { Db } from '../types.js';++export function up(db: Db): void {+ db.exec(`+ CREATE TABLE IF NOT EXISTS custom_model_tombstones (+ endpoint_scope TEXT NOT NULL,+ model_id TEXT NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ PRIMARY KEY (endpoint_scope, model_id)+ );+ `);+}++export function down(db: Db): void {+ db.exec('DROP TABLE IF EXISTS custom_model_tombstones;');+}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex d44f9b1e..6c2232ec 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -17,6 +17,7 @@ import { registerCustomModels, registerCustomChatModels } from '../services/custimport { discoverEndpointModels, probeEndpointModel, ModelDiscoveryError } from '../services/model-discovery.js';import { probeEmbeddingDimensions, registerCustomEmbeddingModel } from '../services/embeddings.js';import { endpointScopeForBaseUrl, normalizeBaseUrl } from '../lib/endpoint-scope.js';+import { recordCustomModelTombstone } from '../services/custom-model-tombstone.js';import type { Db } from '../db/types.js';import { parseModelScope } from '../lib/model-scope.js';import { KEY_PROXY_URL_ERROR, KEY_PROXY_URL_MAX, decryptProxyUrl, encryptProxyUrl, isValidKeyProxyUrl, maskProxyUrl } from '../lib/key-proxy.js';@@ -1318,6 +1319,12 @@ keysRouter.delete('/:id', (req: Request, res: Response) => {// so they never linger in the fallback chain forever (#189).if (row.platform === 'custom') {const defaultEmbedding = db.prepare("SELECT value FROM settings WHERE key = 'embeddings_default_family'").get() as { value: string } | undefined;+ // #926: the scheduled custom-model sync only knows a model by "is it in+ // the table yet". Without a tombstone, a key the operator deleted to get+ // rid of its models would have them all re-registered by the next pass.+ const scope = endpointScopeForBaseUrl(row.base_url);+ const doomed = db.prepare("SELECT model_id FROM models WHERE platform = 'custom' AND key_id = ?").all(id) as { model_id: string }[];+ for (const m of doomed) recordCustomModelTombstone(db, scope, m.model_id);db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom' AND key_id = ?)").run(id);db.prepare("DELETE FROM models WHERE platform = 'custom' AND key_id = ?").run(id);db.prepare("DELETE FROM embedding_models WHERE platform = 'custom' AND key_id = ?").run(id);diff --git a/server/src/routes/models.ts b/server/src/routes/models.tsindex bd6df62f..c03a0e7e 100644--- a/server/src/routes/models.ts+++ b/server/src/routes/models.ts@@ -13,7 +13,8 @@ import {} from '../services/model-state.js';import { pruneUnavailableSavedFusionConfig } from '../services/fusion.js';import { getActiveProfileId } from '../services/profile-models.js';-import { qualifiedModelMemberId } from '../lib/endpoint-scope.js';+import { endpointScopeOfKey, qualifiedModelMemberId } from '../lib/endpoint-scope.js';+import { recordCustomModelTombstone } from '../services/custom-model-tombstone.js';export const modelsRouter = Router();@@ -80,13 +81,16 @@ modelsRouter.delete('/custom/:id', (req: Request, res: Response) => {}const db = getDb();- const row = db.prepare("SELECT id, key_id FROM models WHERE id = ? AND platform = 'custom'").get(id) as { id: number; key_id: number | null } | undefined;+ const row = db.prepare("SELECT id, key_id, model_id FROM models WHERE id = ? AND platform = 'custom'").get(id) as { id: number; key_id: number | null; model_id: string } | undefined;if (!row) {res.status(404).json({ error: { message: `Unknown custom model ${id}` } });return;}const remove = db.transaction(() => {+ // #926: keep this deletion across the scheduled custom-model sync, or the+ // next daily pass re-registers a model the operator removed on purpose.+ recordCustomModelTombstone(db, endpointScopeOfKey(db, row.key_id), row.model_id);db.prepare('DELETE FROM fallback_config WHERE model_db_id = ?').run(id);db.prepare("DELETE FROM models WHERE id = ? AND platform = 'custom'").run(id);deleteUnusedCustomEndpointKey(db, row.key_id);@@ -189,6 +193,10 @@ modelsRouter.delete('/:id', (req: Request, res: Response) => {const remove = db.transaction(() => {if (isCatalogManagedModel(row)) {recordCatalogModelTombstone(db, 'chat', row.platform, row.model_id);+ } else if (row.platform === 'custom') {+ // #926: same "keep it deleted" contract for custom relay models — the+ // scheduled custom-model sync must not resurrect this row.+ recordCustomModelTombstone(db, endpointScopeOfKey(db, row.key_id), row.model_id);}db.prepare('DELETE FROM fallback_config WHERE model_db_id = ?').run(id);db.prepare('DELETE FROM models WHERE id = ?').run(id);diff --git a/server/src/services/custom-model-register.ts b/server/src/services/custom-model-register.tsindex 9589d4fd..ebe26b41 100644--- a/server/src/services/custom-model-register.ts+++ b/server/src/services/custom-model-register.ts@@ -2,6 +2,7 @@ import type { Db } from '../db/types.js';import { resolveCustomEndpointKey, customEndpointKeyIds } from './custom-endpoint.js';import { customModelSeed } from './custom-model-seed.js';import { ensureModelInProfiles } from './profile-models.js';+import { clearCustomModelTombstone } from './custom-model-tombstone.js';import { endpointScopeForBaseUrl } from '../lib/endpoint-scope.js';// ── Shared custom-model registration ─────────────────────────────────────────@@ -92,6 +93,12 @@ export function registerCustomChatModels(const registered: RegisteredCustomModel[] = [];for (const { modelId, displayName, supportsTools, supportsVision } of entries) {+ // #926: this is an EXPLICIT registration (POST /custom, bulk importer or+ // the dashboard's "Fetch models" submit), so it overrides a previous+ // deletion. The scheduled sync never reaches this loop for a tombstoned+ // model — it filters them out in custom-model-sync.ts — so the tombstone+ // can only be lifted here by a human choosing to re-add the model.+ clearCustomModelTombstone(db, endpointScope, modelId);const bound = db.prepare("SELECT key_id FROM models WHERE platform = 'custom' AND model_id = ? AND endpoint_scope = ?",).get(modelId, endpointScope) as { key_id: number | null } | undefined;diff --git a/server/src/services/custom-model-sync.ts b/server/src/services/custom-model-sync.tsindex c5528e6c..23cfb2d2 100644--- a/server/src/services/custom-model-sync.ts+++ b/server/src/services/custom-model-sync.ts@@ -2,6 +2,7 @@ import type { Db } from '../db/types.js';import type { Scheduler } from '../lib/scheduler.js';import { discoverEndpointModels } from './model-discovery.js';import { registerCustomModels, type CustomModelEntry } from './custom-model-register.js';+import { isCustomModelTombstoned } from './custom-model-tombstone.js';import { listCustomEndpoints } from './custom-endpoint.js';import { endpointScopeForBaseUrl } from '../lib/endpoint-scope.js';@@ -59,6 +60,8 @@ export interface CustomModelSyncResult {skipped: number;/** Models skipped because they matched no free pattern (#746). */paidSkipped: number;+ /** Models skipped because the operator deleted them and they must stay deleted (#926). */+ tombstoned: number;failures: Array<{ baseUrl: string; error: string }>;}@@ -66,7 +69,7 @@ export interface CustomModelSyncResult {* that wants a manual pass) can run it directly without waiting for the timer. */export async function runCustomModelSync(db: Db): Promise<CustomModelSyncResult> {const endpoints = listCustomEndpoints(db);- const result: CustomModelSyncResult = { endpoints: endpoints.length, added: 0, skipped: 0, paidSkipped: 0, failures: [] };+ const result: CustomModelSyncResult = { endpoints: endpoints.length, added: 0, skipped: 0, paidSkipped: 0, tombstoned: 0, failures: [] };for (const endpoint of endpoints) {try {@@ -88,6 +91,13 @@ export async function runCustomModelSync(db: Db): Promise<CustomModelSyncResult>result.skipped += 1;continue;}+ // #926: the operator deleted this model (or the key that owned it) and+ // expects it to stay gone. The sync's "add only" contract must not turn+ // a deliberate deletion into the next pass's "new model".+ if (isCustomModelTombstoned(db, scope, model.id)) {+ result.tombstoned += 1;+ continue;+ }// Free-only policy (#746): when FREE_PATTERNS is configured, a model// that matches none of the known-free patterns is presumably paid and// is skipped rather than silently registered.diff --git a/server/src/services/custom-model-tombstone.ts b/server/src/services/custom-model-tombstone.tsnew file mode 100644index 00000000..5e3c3144--- /dev/null+++ b/server/src/services/custom-model-tombstone.ts@@ -0,0 +1,48 @@+// Keep user-deleted custom models deleted across the scheduled model sync.+//+// Issue #926: catalog-managed models carry a tombstone so catalog-sync never+// resurrects a model the user deleted. The scheduled custom-model sync+// (services/custom-model-sync.ts) had no equivalent, so deleting a custom+// relay's model (or its whole endpoint key) was undone by the next sync pass:+// the sync only checks whether the model id is still present in the `models`+// table, and treats a deletion as "new" again.+//+// This module holds the same contract for custom rows, keyed by+// (endpoint_scope, model_id) — the exact identity a custom model row has today+// (#651), so deleting a model on one relay never suppresses the identical id+// on another. A tombstone is "keep it deleted" and is cleared the moment the+// operator EXPLICITLY re-registers that model on the same endpoint.++import type { Db } from '../db/types.js';++export function recordCustomModelTombstone(+ db: Db,+ endpointScope: string,+ modelId: string,+): void {+ db.prepare(`+ INSERT INTO custom_model_tombstones (endpoint_scope, model_id)+ VALUES (?, ?)+ ON CONFLICT(endpoint_scope, model_id)+ DO UPDATE SET created_at = datetime('now')+ `).run(endpointScope, modelId);+}++export function isCustomModelTombstoned(+ db: Db,+ endpointScope: string,+ modelId: string,+): boolean {+ return db.prepare(+ 'SELECT 1 FROM custom_model_tombstones WHERE endpoint_scope = ? AND model_id = ?',+ ).get(endpointScope, modelId) !== undefined;+}++export function clearCustomModelTombstone(+ db: Db,+ endpointScope: string,+ modelId: string,+): void {+ db.prepare('DELETE FROM custom_model_tombstones WHERE endpoint_scope = ? AND model_id = ?')+ .run(endpointScope, modelId);+}