1+ import { describe , it , expect , afterAll } from 'vitest' ;
2+ import * as fs from 'fs' ;
3+ import * as path from 'path' ;
4+ import { Context } from '../src/index' ;
5+
6+ const TEST_DIR = path . join ( __dirname , '.test-tmp' ) ;
7+ const NUM_FILES = 100 ;
8+
9+ describe ( 'Context performance' , ( ) => {
10+ const perfTestDir = TEST_DIR + '-perf-test' ;
11+
12+ afterAll ( ( ) => {
13+ if ( fs . existsSync ( perfTestDir ) ) {
14+ fs . rmSync ( perfTestDir , { recursive : true , force : true } ) ;
15+ }
16+ } ) ;
17+
18+ it ( 'should load 100 random documents within acceptable time' , async ( ) => {
19+ // Create test fixtures directory
20+ const perfFixturesDir = path . join ( __dirname , '.perf-test-fixtures' ) ;
21+ if ( fs . existsSync ( perfFixturesDir ) ) {
22+ fs . rmSync ( perfFixturesDir , { recursive : true , force : true } ) ;
23+ }
24+ fs . mkdirSync ( perfFixturesDir , { recursive : true } ) ;
25+
26+ try {
27+ // Generate 100 random markdown files with 5x longer content
28+ for ( let i = 0 ; i < NUM_FILES ; i ++ ) {
29+ const content = `# Document ${ i } - Performance Testing Content
30+
31+ This is random content number ${ i } . This is a comprehensive performance test document
32+ designed to simulate real-world usage patterns with substantial amounts of text content.
33+ The document contains multiple paragraphs with various topics to ensure the embedding
34+ and search operations are properly tested under realistic load conditions.
35+
36+ ## Section 1: Introduction
37+
38+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt
39+ ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
40+ ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
41+ reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
42+ Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
43+ mollit anim id est laborum.
44+
45+ The quick brown fox jumps over the lazy dog. This is a classic pangram that contains
46+ every letter of the English alphabet at least once. It is often used for testing
47+ typewriters and computer keyboards. In the context of our performance testing, this
48+ sample text serves as filler content to increase the document size and complexity.
49+
50+ ## Section 2: Performance Considerations
51+
52+ Testing performance of loading ${ i } documents into context requires careful consideration
53+ of various factors. These include the computational overhead of embedding generation,
54+ the I/O performance of reading files from disk, and the efficiency of vector storage
55+ operations. Each of these components contributes to the overall execution time and
56+ must be optimized for production use cases.
57+
58+ The keyword density for search optimization should be carefully calibrated. Too many
59+ keywords can lead to overfitting and poor generalization, while too few can result
60+ in suboptimal retrieval performance. Finding the right balance is crucial for building
61+ effective semantic search systems.
62+
63+ ## Section 3: Technical Details
64+
65+ Modern embedding models like BERT, Sentence Transformers, and other transformer-based
66+ architectures provide high-quality semantic representations of text. These models
67+ convert input text into dense vector representations that capture semantic meaning.
68+ The dimensionality of these vectors typically ranges from 128 to 1024 dimensions,
69+ depending on the specific model architecture and training objectives.
70+
71+ When performing similarity search, we typically use cosine similarity or Euclidean
72+ distance to measure the semantic closeness between query and document vectors.
73+ The search operation can be accelerated using various techniques including:
74+ - Approximate Nearest Neighbor (ANN) algorithms
75+ - Hierarchical Navigable Small World (HNSW) graphs
76+ - Inverted File Index (IVF) with product quantization
77+ - Locality-Sensitive Hashing (LSH)
78+
79+ ## Section 4: Use Cases
80+
81+ Semantic search has numerous applications across different domains. In enterprise
82+ settings, it enables employees to quickly find relevant documents, technical
83+ specifications, and knowledge base articles. In e-commerce, it powers product
84+ recommendations and visual search capabilities. In healthcare, it helps researchers
85+ find relevant studies and clinical trial information.
86+
87+ The context system provides a flexible framework for building domain-specific search
88+ applications. By supporting custom loaders, embedders, and rerankers, it can be
89+ adapted to various content types and search requirements. The modular architecture
90+ allows developers to swap out components as needed without major refactoring.
91+
92+ ## Section 5: Optimization Strategies
93+
94+ Several optimization strategies can improve the performance of semantic search systems:
95+
96+ 1. **Caching**: Pre-computed embeddings can be cached to avoid redundant computation.
97+ 2. **Batching**: Processing multiple documents in a batch improves throughput.
98+ 3. **Parallelization**: Using multiple CPU cores or GPU acceleration speeds up processing.
99+ 4. **Incremental Updates**: Only reprocessing changed documents reduces overhead.
100+ 5. **Compression**: Quantizing vectors reduces memory usage and improves cache efficiency.
101+
102+ ## Section 6: Random Data Section
103+
104+ More random text here with keywords: performance, test, load, document, context.
105+ Keyword density for search optimization ${ Math . random ( ) . toString ( 36 ) . substring ( 7 ) } .
106+ Additional padding content to increase file size for more realistic testing scenarios.
107+ The variety of content helps ensure the embedding model handles diverse text properly.
108+ Each document should contain enough variation to simulate complex real-world data.
109+
110+ ## Section 7: Additional Content
111+
112+ Here is some more filler content to further increase the document length and ensure
113+ our performance tests are comprehensive. We want to make sure that the system
114+ can handle not just small documents but also larger ones that contain significant
115+ amounts of text. This is important for production systems that process diverse content.
116+
117+ The embedding process converts this text into numerical representations that capture
118+ semantic meaning. Modern transformer models excel at this task because they have
119+ been pre-trained on massive amounts of text data and can understand contextual
120+ relationships between words and phrases. This deep understanding enables nuanced
121+ semantic matching that goes beyond simple keyword search.
122+
123+ ## Section 8: Conclusion
124+
125+ In conclusion, performance testing is a critical aspect of building robust search
126+ systems. By simulating realistic workloads and measuring actual performance metrics,
127+ we can identify bottlenecks and optimize accordingly. The test document serves
128+ as a valuable tool for validating the system's ability to handle large-scale
129+ content processing efficiently and effectively.
130+
131+ This concludes our comprehensive test document. The content has been expanded
132+ to approximately five times the original length to provide a more realistic
133+ benchmark for performance evaluation. The additional sections include various
134+ types of content that simulate different document structures and complexities.
135+
136+ ## Section 9: Final Notes
137+
138+ Additional paragraph to further increase document length. Understanding the
139+ performance characteristics of your search system is essential for production
140+ deployment. Consider monitoring key metrics like latency, throughput, and resource
141+ utilization to ensure optimal user experience.
142+
143+ ## Section 10: Extra Content
144+
145+ Even more content here. The random string for testing is: ${ Math . random ( ) . toString ( 36 ) . substring ( 7 ) } .
146+ This helps add some variability to the content while keeping the document structure
147+ consistent across all test files. Performance testing is an ongoing process that
148+ should be integrated into the development workflow.
149+ ` ;
150+ fs . writeFileSync ( path . join ( perfFixturesDir , `doc-${ i } .md` ) , content ) ;
151+ }
152+
153+ const ctx = await Context . create ( {
154+ vectorsDir : perfTestDir ,
155+ } ) ;
156+
157+ // Measure load time
158+ const startTime = Date . now ( ) ;
159+ await ctx . load ( 'perf' , path . join ( perfFixturesDir , '*.md' ) ) ;
160+ const endTime = Date . now ( ) ;
161+
162+ const loadTimeMs = endTime - startTime ;
163+ console . log ( `\nPerformance: Loaded ${ NUM_FILES } documents in ${ loadTimeMs } ms` ) ;
164+
165+ // Verify documents were loaded
166+ const results = await ctx . query ( 'test' , { library : 'perf' , topK : 50 } ) ;
167+ expect ( results . length ) . toBeGreaterThan ( 0 ) ;
168+
169+ // Performance assertion: should load 100 docs in under 60 seconds
170+ // This is a reasonable expectation for local embeddings with longer content
171+ expect ( loadTimeMs ) . toBeLessThan ( 60000 ) ;
172+
173+ // Log detailed timing
174+ console . log ( `Average time per document: ${ ( loadTimeMs / NUM_FILES ) . toFixed ( 2 ) } ms` ) ;
175+
176+ await ctx . close ( ) ;
177+ } finally {
178+ // Cleanup fixtures
179+ if ( fs . existsSync ( perfFixturesDir ) ) {
180+ fs . rmSync ( perfFixturesDir , { recursive : true , force : true } ) ;
181+ }
182+ }
183+ } ) ;
184+ } ) ;
0 commit comments