Skip to main content

Portfolio Tracker: Vault Document Embedding System Documentation

Table of Contents

  1. Overview
  2. System Architecture
  3. Database Schema
  4. Document Processing Pipeline
  5. User Interface Components
  6. API Endpoints
  7. Vector Search Implementation
  8. Chat Integration
  9. Security Considerations
  10. Performance Optimizations
  11. Troubleshooting
  12. Future Improvements

Overview

The Vault Document Embedding System is a comprehensive document management solution integrated into the Portfolio Tracker application. It enables users to upload, organize, and semantically search through their documents using advanced natural language processing techniques. The system processes various document types, extracts their text content, splits them into semantically meaningful chunks, generates high-quality vector embeddings, and stores them for efficient retrieval during chat interactions. All document content is securely encrypted at rest, ensuring the highest level of data privacy and security.

Key Features

  • Document Management: Upload, organize, rename, and delete documents
  • Folder Organization: Create and manage folders to organize documents
  • Document Processing: Extract text from various file formats (PDF, DOCX, TXT, CSV, HTML) with robust fallback mechanisms
  • Content Encryption: All document content is encrypted using AES encryption with a dedicated vault document encryption key
  • Decryption on Demand: Document content is only decrypted when needed for search results or display
  • TLS Encryption: All data in transit is encrypted using TLS
  • Database Encryption: Supabase provides encryption at rest for the database
  • Storage Encryption: Uploaded documents are stored with encryption at rest
  • API Key Protection: OpenAI API keys are stored server-side only, never exposed to the client
  • Secure File Naming: Timestamps and sanitized filenames prevent information disclosure
  • Natural Language Search: Find relevant document sections based on natural language queries with similarity threshold optimizations
  • Chat Integration: Reference document content in chat conversations with proper citations and formatted displays
  • Real-time Status Updates: Track document processing status with visual indicators
  • Enhanced Markdown Rendering: Display document content with tables, code blocks, and other rich formatting

System Architecture

The Vault Document Embedding System follows a layered architecture with a strong focus on security and performance:
  1. Presentation Layer: React components in the Next.js frontend with optimized hooks for document operations
  2. API Layer: Next.js API routes for handling document operations using hybrid processing approach
  3. Service Layer: Document processing and embedding generation logic with content encryption
  4. Data Layer: Supabase database with pgvector extension for vector storage and search

Hybrid Processing Approach

The system implements a hybrid client-server architecture that balances performance and security:
  1. Client-side Operations:
    • Direct Supabase client access for status updates and document management
    • Background processing status monitoring with polling
    • UI state management with optimistic updates
  2. Server-side Processing:
    • Computationally intensive operations (text extraction, embedding generation)
    • Secure handling of sensitive content with encryption
    • Background processing for large documents

Technology Stack

  • Frontend: Next.js 14+, React, TanStack Query, Tailwind CSS
  • Backend: Next.js API routes, LangChain document loaders
  • Database: Supabase with pgvector extension for similarity search
  • Authentication: Clerk
  • Storage: Supabase Storage with secure path generation
  • Embeddings: OpenAI text-embedding-3-small model (1536 dimensions)
  • Document Processing: LangChain, pdf-parse, mammoth
  • Security: AES encryption for document content
  • Markdown Rendering: react-markdown with remark-gfm for tables and react-syntax-highlighter for code blocks

Data Flow

  1. User uploads a document through the UI
  2. Document metadata is stored in the database and the file in Supabase Storage
  3. Document processing is initiated in the background
  4. Text is extracted, chunked, and embedded
  5. Embeddings are stored in the database
  6. UI reflects the processing status in real-time
  7. Documents become searchable in the chat interface

Database Schema

The system uses three primary tables in Supabase:

vault_folders

Stores information about document folders for organization.

vault_documents

Stores metadata about uploaded documents.

vault_document_chunks

Stores the text chunks and their embeddings for semantic search.

Document Processing Pipeline

The document processing pipeline is implemented in the central /app/api/document-processor/route.ts file and consists of several key stages:

1. Document Upload and Storage Path Architecture

When a user uploads a document, the useUploadDocumentSync hook in /hooks/mutations/use-upload-document-sync.ts handles the process with an enhanced security-focused storage path architecture:
The document is first uploaded to Supabase Storage, and its metadata is stored in the vault_documents table with initial processing_status set to ‘pending’.

2. Processing Initiation

After upload, the document processing is initiated via the /api/vault/process-document endpoint:
The processing endpoint (/app/api/vault/process-document/route.ts) initiates background processing:

2. Fallback Text Search Mechanism

The system includes a robust fallback text search mechanism to ensure search functionality even when vector search fails:
This fallback mechanism ensures that users can still find relevant documents even if there are issues with the vector search functionality, providing a more resilient search experience.

3. Text Extraction

The extractTextFromDocument function in /lib/document-processor.ts handles text extraction from various file types:
The system supports multiple file types with robust fallback mechanisms and production-ready error handling:
  • PDF: Primary extraction using PDFLoader from LangChain, with pdf-parse as a fallback mechanism. The system includes comprehensive error handling and detailed metadata extraction:
  • DOCX: Primary extraction using DocxLoader from LangChain, with mammoth as a fallback mechanism if DocxLoader fails. This dual approach ensures maximum compatibility with different Word document formats and structures:
  • TXT: Direct text extraction with improved error handling
  • CSV: Using CSVLoader from LangChain with direct text extraction as fallback
  • HTML: Direct text extraction to preserve content
All extraction methods now include comprehensive error handling with the updateDocumentWithError and updateDocumentStatus functions to provide detailed status tracking and recovery mechanisms. The system only allows users to upload file types that can be successfully processed, chunked, and embedded. This ensures that all documents in the vault can be properly searched and referenced in the chat interface.

4. Text Chunking

The splitDocumentsIntoChunks function divides documents into semantically meaningful chunks with comprehensive documentation and production-ready error handling:
Key features of the production-ready chunking process:
  • Semantic Chunking: Uses LangChain’s RecursiveCharacterTextSplitter to create chunks that preserve semantic meaning
  • Configurable Parameters: Chunk size (1000 characters) and overlap (200 characters) are optimized for the embedding model
  • Hierarchical Separators: Uses a hierarchy of separators (paragraphs, newlines, sentences, spaces) to preserve context
  • Enhanced Metadata: Includes document name, folder information, page numbers, and source details for better citations
  • Comprehensive Documentation: Detailed JSDoc comments explain the purpose and behavior of the function
  • Robust Error Handling: Includes error recovery mechanisms and status tracking

5. Embedding Generation

The generateEmbeddings function creates vector embeddings using OpenAI’s model:
We use the text-embedding-3-small model because:
  • It provides high-quality embeddings with 1536 dimensions
  • Offers a good balance between quality and cost
  • Has strong performance for semantic search applications

6. Storage in Database

The storeDocumentChunks function saves chunks and their embeddings to the database:

User Interface Components

The Vault UI is composed of several React components with enhanced rendering capabilities:

Vault Page (/app/vault/page.tsx)

The main container component that orchestrates the vault experience:

Folder List (/app/vault/components/folder-list.tsx)

Displays and manages folders:

Document List (/app/vault/components/document-list.tsx)

Displays documents with processing status indicators:

Upload Document Dialog (/app/vault/components/upload-document.tsx)

Handles document uploads with drag-and-drop support for supported file types (PDF, DOCX, TXT, CSV, HTML):

Status Polling Mechanism

The document list implements a polling mechanism to update processing status:

API Endpoints and Client-Side Data Access

The system uses a hybrid approach for data access, combining API endpoints for complex operations and direct client-side Supabase access for simpler operations:

API Endpoints

These operations require server-side processing or access to service role keys:

Document Management

  • Document Processor: /api/document-processor - Central API for document processing with text extraction, chunking, and embedding generation
  • Delete Document: /api/vault/admin-delete - Admin endpoint to securely remove documents from storage
  • Download Document: /api/vault/download-document - Retrieves files from storage

Deletion Process

Document deletion follows a secure two-step process:
  1. Client-Side Preparation:
  2. Server-Side Deletion:

Folder Management

  • Create Folder: /api/vault/create-folder - Creates new folders
  • Delete Folder: /api/vault/delete-folder - Removes folders and contained documents

Client-Side Data Access

The following operations use direct Supabase client access from React hooks, eliminating the need for API routes:

User Preferences

  • Mark Vault as Read: Updates the has_read_vault flag in the user’s profile via the useUserInfo hook

Search and Retrieval

  • Search Documents: Uses the useSearchDocuments hook to perform vector similarity search directly from the client
    • Includes automatic fallback to text search when vector search fails
    • Provides loading states and error handling via React Query
    • Maintains the same search capabilities as the previous API-based implementation

Document Processing Status

  • Check Processing Status: Uses the useDocumentProcessingStatus hook to poll for document processing status
    • Automatically handles polling with configurable intervals
    • Includes automatic fixing of inconsistent document states
    • Provides detailed status information including counts by status type
    • Stops polling automatically when all documents are processed

Document Management

  • Rename Document: Updates document names directly via the useRenameDocument hook

Folder Management

  • Rename Folder: Updates folder names directly via the useRenameFolder hook

Process Document Endpoint

The /api/vault/process-document/route.ts endpoint is particularly important as it manages the document processing pipeline:
Key design decisions:
  • Background Processing: Processing happens asynchronously to avoid blocking the API response
  • Status Tracking: Document status is updated at each stage of processing
  • Error Handling: Comprehensive error handling with status updates

Document Processing Status Hook

The useDocumentProcessingStatus hook provides client-side polling for document processing status:

Vector Search Implementation

The system uses Supabase’s pgvector extension for vector similarity search: A custom SQL function match_documents is implemented in Supabase:
This function:
  • Takes a query embedding vector and search parameters
  • Performs cosine similarity search using the <=> operator
  • Joins with document and folder tables to include metadata
  • Filters by user ID for security
  • Returns the most relevant chunks sorted by similarity

Document Search Implementation

The searchDocuments function in /lib/document-processor.ts has been optimized for production with improved error handling and fallback mechanisms:

Chat Integration

The document search is integrated with the chat system to provide document-based answers with enhanced formatting:

Chat API Route

The /app/api/chat/route.ts file integrates document search into the chat with improved formatting and citation:
When the AI assistant needs to reference documents, it calls the searchVaultDocuments function, which:
  1. Searches for relevant document chunks using vector similarity
  2. Formats the content with proper markdown for better readability
  3. Includes document and folder names for proper citation
  4. Returns the formatted results to the assistant

System Prompt Enhancement

The chat system prompt includes enhanced guidelines for document citations and response formatting:

Direct Response Style

The system prompt also instructs the AI to provide direct answers without acknowledgment phrases:

Security Considerations

Security is a paramount concern for the Vault Document System due to the sensitive nature of the stored documents. The system implements several advanced security measures:

User-Based Access Control

  • Document storage paths use folder UUIDs instead of user IDs for enhanced privacy
  • Database RLS policies ensure users can only access their own documents
  • Admin endpoints use service role keys to manage storage without exposing credentials to clients
This ensures users can only access their own documents.

Server-Side Validation

API endpoints validate requests on the server side:

Secure Storage Access

Document storage uses Supabase Storage with proper access controls:

Performance Optimizations

The system includes several optimizations to ensure responsive performance even with large document collections:

Document Processing

  • Hybrid Processing Model: Combines client-side operations for UI updates with server-side processing for computation-intensive tasks
  • Background Processing: Documents are processed asynchronously to prevent UI blocking
  • Batched Embedding Generation: Embeddings are generated in batches to avoid rate limits
  • Chunking Strategy: Documents are split into optimal-sized chunks (1000 characters with 200 character overlap) for better semantic understanding
  • Status Polling: Processing status is polled efficiently to provide real-time updates without overloading the server
  • Production-Ready Logging: Console logs have been removed/commented for production environments
  • pgvector Indexing: Utilizes pgvector’s HNSW indexing for faster search on large collections
  • Custom RPC Function: Avoids multiple round trips by performing complex queries in a single database call
  • Increased Similarity Threshold: Only returns results above a higher similarity threshold (0.6) for better precision
  • Removed Fallback Complexity: Simplified fallback strategy for more reliable and predictable search behavior
  • Result Limiting: Limits search results to the most relevant matches
  • Efficient Content Handling: Only decrypts content for the specific chunks needed

Troubleshooting

Common issues and their solutions:

Document Processing Issues

If document processing gets stuck or fails:
  1. Check the document’s processing_status in the database
  2. Verify file permissions in Supabase Storage
  3. Check server logs for errors during text extraction
  4. Ensure the document format is supported

Fallback Mechanism for DOCX and PDF Processing

The system implements a fallback mechanism for DOCX and PDF processing:
  • DOCX Fallback: If the primary DOCX processor (DocxLoader) fails, the system falls back to mammoth for text extraction.
  • PDF Fallback: If the primary PDF processor (pdf-parse) fails, the system falls back to an alternative PDF parser.
This ensures that document processing is robust and can handle different document formats and processing errors.

Status Inconsistencies

If the UI shows incorrect processing status:
  1. The check-processing-status endpoint includes automatic fixing of inconsistent states:

File Download Issues

If file downloads fail:
  1. The document processor includes fallback mechanisms for file paths:

Document Extraction Issues

If text extraction from documents fails:
  1. The system implements robust fallback mechanisms for different document types:
  1. Check if the document format is supported and properly formatted
  2. For complex documents, try simplifying them before upload

Future Improvements

Planned enhancements to the system include:

Document Processing

  • OCR Integration: Extract text from images and scanned documents
  • Better PDF Handling: Improved extraction of structured content from PDFs
  • Advanced Document Preprocessing: Text normalization and noise reduction techniques
  • Additional Metadata Extraction: Enhanced extraction of document structure and metadata
  • Improved Processing Status UI: More granular status reporting during processing
  1. Caching Mechanism: Add caching for frequently accessed documents and search results
  2. Batch Processing: Implement batch processing for multiple documents
  3. User Feedback Loop: Allow users to rate search result relevance to improve future searches
  4. Document Versioning: Track document versions and changes over time
  5. Enhanced Security: Add document-level access controls and sharing capabilities

This documentation provides a comprehensive overview of the Vault Document Embedding System in the Portfolio Tracker application. It covers the architecture, implementation details, and design decisions to help developers understand and extend the system.