@@ -426,9 +426,7 @@ export async function processDocumentAsync(
426426 try {
427427 logger . info ( `[${ documentId } ] Starting document processing: ${ docData . filename } ` )
428428
429- // Single JOIN fetches everything we'll need: KB processing config, workspace
430- // billing context, and the document's tag values (folded onto the embedding
431- // rows later). Replaces three separate SELECTs.
429+ // KB config + workspace billing + doc tags in one JOIN (was 3 SELECTs).
432430 const contextRows = await db
433431 . select ( {
434432 userId : knowledgeBase . userId ,
@@ -589,8 +587,7 @@ export async function processDocumentAsync(
589587 }
590588 }
591589
592- // Document tag values are stable from upload time and were prefetched in
593- // the JOIN above — reuse them instead of issuing another SELECT.
590+ // Tag values prefetched above; reuse for the embedding rows.
594591 const documentTags = ctx
595592
596593 logger . info ( `[${ documentId } ] Embeddings generated, creating embedding records with tags` )
@@ -782,10 +779,11 @@ export async function createDocumentRecords(
782779 throw new Error ( 'Knowledge base not found' )
783780 }
784781
785- // Load tag definitions once for the whole batch (avoids N+1 across docs)
786- // and reuses the transaction's connection so we don't double-checkout
787- // while holding the KB FOR UPDATE lock.
788- const tagDefinitions = await loadTagDefinitions ( knowledgeBaseId , tx )
782+ // One load per batch (was N+1); skip entirely if no doc carries tags.
783+ const hasTaggedDocs = documents . some ( ( d ) => d . documentTagsData )
784+ const tagDefinitions = hasTaggedDocs
785+ ? await loadTagDefinitions ( knowledgeBaseId , tx )
786+ : ( new Map ( ) as TagDefinitionsByName )
789787
790788 const now = new Date ( )
791789 const documentRecords = [ ]
0 commit comments