Files
OmniRoute/tests/unit/db-playground-presets.test.ts
Paijo 4b06761ad5 feat(api): add pagination params to 8 DB modules + recharts code-split (#7046)
* perf: extract recharts into dynamic import wrappers

Bundle recharts behind next/dynamic boundaries to prevent its
large module graph from being included in the initial JS payload.

- CostOverviewTab.tsx → dynamic(() => import('./components/CostCharts'))
- ProviderUtilizationTab.tsx → dynamic(() => import('./components/ProviderCharts'))
- BurnRateChart.tsx → dynamic(() => import('./components/BurnRateChartInner'))
- Created 3 wrapper files with 'use client' and all recharts imports

Reduces initial bundle by ~35 kB (recharts + dependencies).

* perf: add pagination (limit/offset) to apiKeys, combos, providers, provider-nodes

Add optional limit/offset parameters to DB list functions and their
API route handlers. All list functions now return { items, total } when
called with parameters; backward compatible when called without args.

Affected modules:
- lib/db/apiKeys.ts      - listApiKeys, getApiKeysByGroup
- lib/db/combos.ts       - listCombos
- lib/db/providers.ts    - listProviders, getProvidersByGroup
- lib/db/providers/nodes.ts - listProviderNodes, getProviderNodesByGroup
- Corresponding API routes pass through query params

Reduces memory pressure on large datasets by returning one page at a time.

* perf: add pagination (limit/offset) to webhooks, proxies, modelComboMappings, playgroundPresets

Add optional limit/offset parameters to DB list functions and their
API route handlers for the remaining data modules.

Affected modules:
- lib/db/webhooks.ts         - getWebhooks returns { webhooks, total }
- lib/db/proxies.ts          - listProxies
- lib/db/modelComboMappings.ts - listMappings
- lib/db/playgroundPresets.ts - listPresets
- Corresponding API routes pass through query params
- Re-exports updated: lib/localDb.ts, models/index.ts

Backward compatible: calling without args returns all rows.

* perf: batch pool building and add pagination to quotaPools

Replace per-pool N+1 queries with batch-loading pattern.

- Added batchBuildPools(rows) — collects all pool IDs, does 2 batch
  queries (allocations + connections) instead of 2N individual queries
- getPoolsByGroup and listPools now use batchBuildPools
- Added optional limit/offset pagination params
- Fixed SQLite OFFSET-syntax bug: only emit OFFSET when LIMIT also present
- Added quota-pools.test.ts with 10 tests covering pagination edge cases,
  batch loading, and the offset-without-limit guard

Reduces pool-page query count from 2N+1 to 3 (constant).

* perf: replace manual offset/limit parsing with Zod paginationSchema in combos GET handler

* fix: replace manual Number()/parseInt pagination with paginationSchema

Endpoints: model-combo-mappings, playground/presets, provider-nodes.
Uses existing Zod schema with z.coerce.number() for proper validation.

* chore: bump proxies.ts frozen baseline 1177->1208 for perf/api-pagination

PR #7046 backward-compatible pagination refactor grew proxies.ts
by +31 lines (1177->1208). Entries return plain array when no
pagination params provided, {items,total} when pagination requested.

* fix(db): finish listProxies()/getWebhooks() pagination shape migration

The pagination refactor changed listProxies(), listPools(),
getModelComboMappings(), listPlaygroundPresets() and getWebhooks() to
return a paginated envelope ({ items, total } / { webhooks, total })
instead of a bare array, but left three real production callers and
several tests on the old array-shaped API:

- src/lib/proxyEgress.ts (validateProxyPool default listProxies impl)
  iterated the envelope directly -> "is not iterable" at runtime, hit
  by /api/settings/proxies/egress (no injected deps).
- src/lib/proxyHealth/scheduler.ts (sweep()) read proxies.length on the
  envelope (undefined), so the health-check sweep silently processed
  zero proxies every run.
- open-sse/utils/proxyFallback.ts (getProxyCandidates()) iterated the
  envelope inside a try/catch that swallowed the resulting TypeError,
  so every user-configured proxy silently vanished from the fallback
  candidate list.

Also fixes two TS2558/TS2339 typecheck errors in proxies.ts/webhooks.ts
(db.prepare<T>() generic not supported by this DB wrapper — cast the
query result instead, matching the existing pattern in both files) and
trims one blank re-export separator line in localDb.ts to stay within
the frozen file-size ratchet after 4 new *Count() exports.

Updates the pre-existing unit tests that called the changed functions
directly (db-quota-pools, quota-groups-migration, quota-pool-connections,
quota-pool-delete-prune, db-webhooks, model-combo-mappings-db,
db-playground-presets, db-proxies-crud, proxy-batch-routes-5918,
proxy-registry, error-message-sanitization) to destructure the new
envelope shape instead of treating the result as an array.

Implements the small, well-scoped performance-mark/measure
instrumentation ("omni-pipeline-start"/"omni-pipeline-end"/"omni-pipeline")
that tests/unit/chatcore-streaming-pipeline.test.ts already asserted for
assembleStreamingPipeline() but that had no corresponding source change.

Adds three new regression tests (TDD: each reproduces its bug against
the pre-fix code before the corresponding fix, then passes) covering
the three real production callers above:
tests/unit/proxy-egress-validate-pool-default.test.ts,
tests/unit/proxy-health-scheduler-listproxies-shape.test.ts,
tests/unit/proxy-fallback-candidates-listproxies-shape.test.ts.

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* fix: resolve rebase conflict in proxies.ts — keep hasBlockingProxyAssignment but drop duplicate extraction leftovers

- Removed duplicate resolveScopePoolInternal, resolveProxyForConnectionFromRegistry,
  resolveProxyForScopeFromRegistry already extracted to proxies/rotation.ts
- Removed duplicate hasBlockingProxyAssignment function body already re-exported from proxies/guards.ts
- Removed duplicate PROXY_ALIVE_PREDICATE import
- All typechecks and 45 affected tests pass

* fix(test): account for _reorderConnections in pagination test expectedOrder

createProviderConnection calls _reorderConnections after every insert
which reassigns priorities sequentially. The test was assuming creation
order determines priority order, leading to incorrect expected results.

Fix: query the DB after all inserts and use the actual priority order.

Also removes debug console.log from getRawProviderConnections.

* chore: remove debug tmp-*.mjs files left in PR branch

* test(proxy): migrate the dedup test to the paginated listProxies() shape

#7046 changed listProxies() to return { items, total }, and updated every
production caller plus three of the four test files — tests/unit/proxy-bulk-import-dedup-7594.test.ts
was missed, so its four `listed.length` assertions read `undefined` and the
file went red on the merge train (it passes on the pure release tip).

Test-only: destructure `{ items: listed }` at the four callsites. Verified
proxyEgress.ts needs no change — its local deps shim already unwraps .items,
and tests/unit/proxy-egress-validate-pool-default.test.ts guards exactly that.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
2026-07-20 10:07:49 -03:00

367 lines
13 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-db-playground-presets-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const presetsDb = await import("../../src/lib/db/playgroundPresets.ts");
const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
async function resetStorage() {
core.resetDbInstance();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: any) {
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
// ─── Migration idempotency ───────────────────────────────────────────────────
test("migration 076 is idempotent — running it twice does not throw", () => {
// First run: triggered implicitly by getDbInstance()
const db1 = core.getDbInstance();
const tableExists1 = db1
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='playground_presets'")
.get();
assert.ok(tableExists1, "table should exist after first init");
// Second run: resetDbInstance + re-init simulates running migrations again
core.resetDbInstance();
const db2 = core.getDbInstance();
const tableExists2 = db2
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='playground_presets'")
.get();
assert.ok(tableExists2, "table should still exist after second init (idempotent)");
});
test("migration 076 creates both indexes", () => {
const db = core.getDbInstance();
const nameIdx = db
.prepare(
"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_playground_presets_name'"
)
.get();
const endpointIdx = db
.prepare(
"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_playground_presets_endpoint'"
)
.get();
assert.ok(nameIdx, "idx_playground_presets_name should exist");
assert.ok(endpointIdx, "idx_playground_presets_endpoint should exist");
});
// ─── Full CRUD lifecycle ─────────────────────────────────────────────────────
test("create → list → get → update (partial) → delete → get returns null", () => {
// CREATE
const preset = presetsDb.createPlaygroundPreset({
name: "My Preset",
endpoint: "chat.completions",
model: "gpt-4o",
system: "You are a helpful assistant.",
params: { temperature: 0.7, max_tokens: 1024 },
});
assert.ok(UUID_V4_REGEX.test(preset.id), "id should be a valid UUID v4");
assert.equal(preset.name, "My Preset");
assert.equal(preset.endpoint, "chat.completions");
assert.equal(preset.model, "gpt-4o");
assert.equal(preset.system, "You are a helpful assistant.");
assert.deepEqual(preset.params, { temperature: 0.7, max_tokens: 1024 });
assert.ok(typeof preset.created_at === "string" && preset.created_at.length > 0);
// LIST — should contain the created preset
const { items: list } = presetsDb.listPlaygroundPresets();
assert.equal(list.length, 1);
assert.equal(list[0].id, preset.id);
// GET by id
const fetched = presetsDb.getPlaygroundPreset(preset.id);
assert.ok(fetched !== null, "getPlaygroundPreset should return the created row");
assert.equal(fetched.id, preset.id);
assert.equal(fetched.name, "My Preset");
// UPDATE — partial patch (only name + params)
const updated = presetsDb.updatePlaygroundPreset(preset.id, {
name: "Updated Preset",
params: { temperature: 0.9 },
});
assert.ok(updated !== null, "updatePlaygroundPreset should return updated row");
assert.equal(updated.name, "Updated Preset");
assert.deepEqual(updated.params, { temperature: 0.9 });
// Untouched fields remain
assert.equal(updated.endpoint, "chat.completions");
assert.equal(updated.model, "gpt-4o");
assert.equal(updated.system, "You are a helpful assistant.");
// DELETE
const deleted = presetsDb.deletePlaygroundPreset(preset.id);
assert.equal(deleted, true);
// GET after delete
const afterDelete = presetsDb.getPlaygroundPreset(preset.id);
assert.equal(afterDelete, null);
});
// ─── params JSON round-trip ──────────────────────────────────────────────────
test("params object is serialized to params_json and correctly deserialized", () => {
const input = { temperature: 0.7, max_tokens: 2048, top_p: 0.95, seed: 42 };
const preset = presetsDb.createPlaygroundPreset({
name: "JSON Params",
endpoint: "chat.completions",
model: "gpt-4o-mini",
system: null,
params: input,
});
const fetched = presetsDb.getPlaygroundPreset(preset.id);
assert.ok(fetched !== null);
assert.deepEqual(fetched.params, input);
});
test("empty params object serializes to {} and deserializes correctly", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "Empty Params",
endpoint: "embeddings",
model: "text-embedding-ada-002",
system: null,
params: {},
});
const fetched = presetsDb.getPlaygroundPreset(preset.id);
assert.ok(fetched !== null);
assert.deepEqual(fetched.params, {});
});
// ─── UUID v4 validation ──────────────────────────────────────────────────────
test("generated id matches UUID v4 pattern", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "UUID Test",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
assert.match(preset.id, UUID_V4_REGEX);
});
test("two presets get distinct UUIDs", () => {
const a = presetsDb.createPlaygroundPreset({
name: "A",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
const b = presetsDb.createPlaygroundPreset({
name: "B",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
assert.notEqual(a.id, b.id);
assert.match(a.id, UUID_V4_REGEX);
assert.match(b.id, UUID_V4_REGEX);
});
// ─── Not-found paths ─────────────────────────────────────────────────────────
test("getPlaygroundPreset with non-existent id returns null", () => {
const result = presetsDb.getPlaygroundPreset("00000000-0000-4000-8000-000000000000");
assert.equal(result, null);
});
test("deletePlaygroundPreset with non-existent id returns false", () => {
const result = presetsDb.deletePlaygroundPreset("00000000-0000-4000-8000-000000000001");
assert.equal(result, false);
});
test("updatePlaygroundPreset with non-existent id returns null", () => {
const result = presetsDb.updatePlaygroundPreset("00000000-0000-4000-8000-000000000002", {
name: "Ghost",
});
assert.equal(result, null);
});
// ─── Timestamp preservation ──────────────────────────────────────────────────
test("created_at is preserved after update", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "Timestamp Test",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
const originalTimestamp = preset.created_at;
const updated = presetsDb.updatePlaygroundPreset(preset.id, { name: "Updated Name" });
assert.ok(updated !== null);
assert.equal(updated.created_at, originalTimestamp, "created_at must not change on update");
});
// ─── List ordering ───────────────────────────────────────────────────────────
test("listPlaygroundPresets returns newest first", () => {
// Create two presets; DB ordering is by created_at DESC
// Use a small delay approach: insert them sequentially and trust SQLite ordering
const first = presetsDb.createPlaygroundPreset({
name: "First",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
const second = presetsDb.createPlaygroundPreset({
name: "Second",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
const { items: list } = presetsDb.listPlaygroundPresets();
assert.equal(list.length, 2);
// When timestamps are identical, both rows are present; just verify both ids are there
const ids = list.map((p) => p.id);
assert.ok(ids.includes(first.id));
assert.ok(ids.includes(second.id));
});
// ─── updatePlaygroundPreset with empty patch ─────────────────────────────────
test("updatePlaygroundPreset with empty patch returns current row unchanged", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "No Change",
endpoint: "chat.completions",
model: "gpt-4o",
system: "System",
params: { temperature: 0.5 },
});
const result = presetsDb.updatePlaygroundPreset(preset.id, {});
assert.ok(result !== null);
assert.equal(result.name, "No Change");
assert.equal(result.system, "System");
assert.deepEqual(result.params, { temperature: 0.5 });
});
// ─── system field null/non-null handling ────────────────────────────────────
test("system field accepts null and non-null values correctly", () => {
const withSystem = presetsDb.createPlaygroundPreset({
name: "With System",
endpoint: "chat.completions",
model: "gpt-4o",
system: "Be helpful",
params: {},
});
const withoutSystem = presetsDb.createPlaygroundPreset({
name: "Without System",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
assert.equal(withSystem.system, "Be helpful");
assert.equal(withoutSystem.system, null);
});
test("updatePlaygroundPreset can set system to null", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "Has System",
endpoint: "chat.completions",
model: "gpt-4o",
system: "Initial system",
params: {},
});
const updated = presetsDb.updatePlaygroundPreset(preset.id, { system: null });
assert.ok(updated !== null);
assert.equal(updated.system, null);
});
// ─── Update individual scalar fields ─────────────────────────────────────────
test("updatePlaygroundPreset can patch endpoint field", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "Endpoint Patch",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
const updated = presetsDb.updatePlaygroundPreset(preset.id, { endpoint: "embeddings" });
assert.ok(updated !== null);
assert.equal(updated.endpoint, "embeddings");
assert.equal(updated.model, "gpt-4o");
});
test("updatePlaygroundPreset can patch model field", () => {
const preset = presetsDb.createPlaygroundPreset({
name: "Model Patch",
endpoint: "chat.completions",
model: "gpt-4o",
system: null,
params: {},
});
const updated = presetsDb.updatePlaygroundPreset(preset.id, { model: "gpt-4o-mini" });
assert.ok(updated !== null);
assert.equal(updated.model, "gpt-4o-mini");
assert.equal(updated.endpoint, "chat.completions");
});
// ─── Corrupted params_json fallback ─────────────────────────────────────────
test("corrupted params_json in DB row is recovered to empty object", () => {
// Insert a row with invalid JSON via raw SQLite to simulate DB corruption
const db = core.getDbInstance();
const id = "corrupted-params-test-id-9999";
db.prepare(
"INSERT INTO playground_presets (id, name, endpoint, model, system, params_json) VALUES (?, ?, ?, ?, ?, ?)"
).run(id, "Corrupted", "chat.completions", "gpt-4o", null, "INVALID_JSON{{{{");
const fetched = presetsDb.getPlaygroundPreset(id);
assert.ok(fetched !== null);
assert.deepEqual(fetched.params, {}, "corrupted params_json should fall back to {}");
});