Project NOMAD is an offline-first knowledge and education server. Wikipedia, thousands of books, courses, maps, and optional local AI, all running on hardware you own with no internet required.
TypeScript
test(kb): extract orphan allowlist into a tested pure fn
John Cortrightd4f0f078c5af
diff --git a/admin/app/services/rag_service.ts b/admin/app/services/rag_service.tsindex f7c35549..38c08e15 100644--- a/admin/app/services/rag_service.ts+++ b/admin/app/services/rag_service.ts@@ -26,7 +26,7 @@ import { join, resolve, sep } from 'node:path'import KVStore from '#models/kv_store'import KbIngestState from '#models/kb_ingest_state'import { decideScanAction, type IngestPolicy } from '../utils/kb_ingest_decision.js'-import { decideOrphans } from '../utils/kb_orphan_decision.js'+import { decideOrphans, filterOrphanCandidates } from '../utils/kb_orphan_decision.js'import { decideContentReindex, type ReindexOutcome } from '../utils/content_reindex_decision.js'import KbRatioRegistry from '#models/kb_ratio_registry'import { decideWarnings } from '../utils/kb_warning_decision.js'@@ -2356,24 +2356,19 @@ export class RagService {// embeddableFiles came back empty, so a filesystem hiccup can't be// misread as "every file was deleted."//- // Allowlisted to sources under the same two roots _discoverKbFiles()- // just scanned to build embeddableFiles — the only roots this sweep- // can make an informed orphan/not-orphan call about. Nomad's own- // bundled docs (README.md + docs/) are embedded by discoverNomadDocs()- // above from outside those roots, so this naturally leaves them alone- // without needing to name them here. A denylist of "everything except- // README/docs" would instead default to purging any future source root- // added outside kb_uploads/zim the first time it appears.- const { kbUploadsPath, zimPath } = this._kbScanRoots()- const kbUploadsPrefix = kbUploadsPath + sep- const zimPrefix = zimPath + sep- const orphanCandidates = [...sourcesInQdrant].filter(- (source) => source.startsWith(kbUploadsPrefix) || source.startsWith(zimPrefix)- )+ // Allowlisted (via filterOrphanCandidates) to sources under the same+ // two roots _discoverKbFiles() just scanned to build embeddableFiles —+ // the only roots this sweep can make an informed orphan/not-orphan+ // call about. Nomad's own bundled docs (README.md + docs/) are+ // embedded by discoverNomadDocs() above from outside those roots, so+ // this naturally leaves them alone without needing to name them here.+ const orphanCandidates = filterOrphanCandidates([...sourcesInQdrant], this._kbScanRoots())const orphans = decideOrphans(orphanCandidates, embeddableFiles)let orphansPurged = 0if (orphans && orphans.length > 0) {- logger.info(`[RAG] Found ${orphans.length} orphaned source(s) with no corresponding file on disk`)+ logger.info(+ `[RAG] Found ${orphans.length} orphaned source(s) with no corresponding file on disk`+ )try {await this.purgeIndexedSources(orphans)orphansPurged = orphans.length@@ -2443,7 +2438,10 @@ export class RagService {`[RAG] Scan results (policy=${policy}): ${filesToEmbed.length} to embed, ${backfilled} backfilled, ${createdRows} new pending, ${createdPending} waiting on user, ${skipped} skipped`)- const orphanNote = orphansPurged > 0 ? `; purged ${orphansPurged} orphaned source${orphansPurged !== 1 ? 's' : ''}` : ''+ const orphanNote =+ orphansPurged > 0+ ? `; purged ${orphansPurged} orphaned source${orphansPurged !== 1 ? 's' : ''}`+ : ''if (filesToEmbed.length === 0) {return {diff --git a/admin/app/utils/kb_orphan_decision.ts b/admin/app/utils/kb_orphan_decision.tsindex 660a4a7d..222a7286 100644--- a/admin/app/utils/kb_orphan_decision.ts+++ b/admin/app/utils/kb_orphan_decision.ts@@ -1,3 +1,5 @@+import { sep } from 'node:path'+/*** Decision for the reverse sweep in `RagService.scanAndSyncStorage`.*@@ -23,3 +25,24 @@ export function decideOrphans(sourcesInQdrant: string[], embeddableFiles: stringconst onDisk = new Set(embeddableFiles)return sourcesInQdrant.filter((source) => !onDisk.has(source))}++/**+ * Narrows Qdrant sources down to the ones decideOrphans() can actually make+ * an informed call about: sources under the same roots `_discoverKbFiles()`+ * scanned to build `embeddableFiles` (kb_uploads, zim). Everything else —+ * Nomad's own bundled docs (README.md + docs/), or any future embedding+ * source root — is left alone here rather than denylisted by name, so a new+ * source root added outside kb_uploads/zim doesn't get treated as an orphan+ * and purged the first time it appears (see issue #1170's docs-collision+ * near-miss for exactly that failure mode).+ */+export function filterOrphanCandidates(+ sourcesInQdrant: string[],+ scanRoots: { kbUploadsPath: string; zimPath: string }+): string[] {+ const kbUploadsPrefix = scanRoots.kbUploadsPath + sep+ const zimPrefix = scanRoots.zimPath + sep+ return sourcesInQdrant.filter(+ (source) => source.startsWith(kbUploadsPrefix) || source.startsWith(zimPrefix)+ )+}diff --git a/admin/tests/unit/kb_orphan_decision.spec.ts b/admin/tests/unit/kb_orphan_decision.spec.tsindex 352684a1..f934a52c 100644--- a/admin/tests/unit/kb_orphan_decision.spec.ts+++ b/admin/tests/unit/kb_orphan_decision.spec.ts@@ -1,7 +1,9 @@import * as assert from 'node:assert/strict'import { test } from 'node:test'-import { decideOrphans } from '../../app/utils/kb_orphan_decision.js'+import { decideOrphans, filterOrphanCandidates } from '../../app/utils/kb_orphan_decision.js'++const SCAN_ROOTS = { kbUploadsPath: '/data/storage/kb_uploads', zimPath: '/data/storage/zim' }test('no sources in Qdrant → no orphans', () => {assert.deepEqual(decideOrphans([], ['/storage/zim/a.zim']), [])@@ -31,3 +33,30 @@ test('every Qdrant source is orphaned when none remain on disk (but disk scan watest('empty disk scan is treated as a transient failure, not "everything was deleted"', () => {assert.equal(decideOrphans(['/storage/zim/a.zim', '/storage/zim/b.zim'], []), null)})++test('filterOrphanCandidates keeps sources under the kb_uploads or zim scan roots', () => {+ assert.deepEqual(+ filterOrphanCandidates(+ ['/data/storage/kb_uploads/a.pdf', '/data/storage/zim/b.zim'],+ SCAN_ROOTS+ ),+ ['/data/storage/kb_uploads/a.pdf', '/data/storage/zim/b.zim']+ )+})++test('filterOrphanCandidates excludes sources outside the scanned roots (e.g. bundled docs)', () => {+ assert.deepEqual(+ filterOrphanCandidates(+ ['/data/README.md', '/data/docs/guide.md', '/data/storage/zim/b.zim'],+ SCAN_ROOTS+ ),+ ['/data/storage/zim/b.zim']+ )+})++test('filterOrphanCandidates does not match a sibling directory that merely shares a root as a string prefix', () => {+ // '/data/storage/zim-backup/...' must not pass just because it starts with+ // the same characters as zimPath — the trailing separator is what makes+ // this a real subpath check rather than a naive string prefix match.+ assert.deepEqual(filterOrphanCandidates(['/data/storage/zim-backup/x.zim'], SCAN_ROOTS), [])+})