-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPHPVectorTest.php
More file actions
393 lines (297 loc) · 12.3 KB
/
Copy pathPHPVectorTest.php
File metadata and controls
393 lines (297 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
declare(strict_types=1);
namespace NeuronAI\PHPVector\Tests;
use NeuronAI\PHPVector\PHPVector;
use NeuronAI\RAG\Document as NeuronDocument;
use PHPVector\VectorDatabase;
use PHPUnit\Framework\TestCase;
use ReflectionProperty;
use function array_diff;
use function array_fill;
use function is_array;
use function is_dir;
use function iterator_to_array;
use function mt_getrandmax;
use function mt_rand;
use function rmdir;
use function scandir;
use function sys_get_temp_dir;
use function uniqid;
use function unlink;
class PHPVectorTest extends TestCase
{
private string $tempDir;
protected function setUp(): void
{
parent::setUp();
$this->tempDir = sys_get_temp_dir() . '/phpvector_test_' . uniqid();
}
protected function tearDown(): void
{
parent::tearDown();
$this->removeDirectory($this->tempDir);
}
private function removeDirectory(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
$path = $dir . '/' . $file;
is_dir($path) ? $this->removeDirectory($path) : unlink($path);
}
rmdir($dir);
}
/**
* Extract the internal VectorDatabase from a PHPVector instance.
*
* The new PHPVector constructor accepts a directory path and manages its own
* VectorDatabase internally (protected property). Tests that need to assert
* document counts or call save() use this helper to reach the inner instance.
*/
private function getDatabase(PHPVector $store): VectorDatabase
{
$ref = new ReflectionProperty(PHPVector::class, 'database');
return $ref->getValue($store);
}
private function createTestEmbedding(int $dimensions = 128): array
{
$embedding = [];
for ($i = 0; $i < $dimensions; $i++) {
$embedding[] = mt_rand() / mt_getrandmax();
}
return $embedding;
}
public function testAddDocumentIncreasesCount(): void
{
$store = new PHPVector($this->tempDir);
$document = new NeuronDocument('Test content');
$document->embedding = $this->createTestEmbedding();
$store->addDocument($document);
$this->assertEquals(1, $this->getDatabase($store)->count());
}
public function testAddDocumentsAddsMultipleDocuments(): void
{
$store = new PHPVector($this->tempDir);
$documents = [
$this->createDocumentWithEmbedding('Document 1'),
$this->createDocumentWithEmbedding('Document 2'),
$this->createDocumentWithEmbedding('Document 3'),
];
$store->addDocuments($documents);
$this->assertEquals(3, $this->getDatabase($store)->count());
}
public function testPersistDocumentsAcrossInstances(): void
{
// Create and persist documents with first instance.
$store = new PHPVector($this->tempDir);
$documents = [
$this->createDocumentWithEmbedding('Persisted document 1'),
$this->createDocumentWithEmbedding('Persisted document 2'),
];
$store->addDocuments($documents);
$this->assertEquals(2, $this->getDatabase($store)->count());
// Open a fresh VectorDatabase from the same path and verify documents persist.
$reopened = VectorDatabase::open($this->tempDir);
$this->assertEquals(2, $reopened->count());
}
public function testSimilaritySearchReturnsResults(): void
{
$store = new PHPVector($this->tempDir);
// Create documents with known embeddings for predictable search
$embedding1 = array_fill(0, 128, 0.0);
$embedding1[0] = 1.0; // First vector points in direction [1, 0, 0, ...]
$embedding2 = array_fill(0, 128, 0.0);
$embedding2[1] = 1.0; // Second vector points in direction [0, 1, 0, ...]
$embedding3 = array_fill(0, 128, 0.0);
$embedding3[0] = 0.9; // Third vector is similar to first
$embedding3[1] = 0.1;
$doc1 = new NeuronDocument('Document about cats');
$doc1->id = 'doc1';
$doc1->embedding = $embedding1;
$doc2 = new NeuronDocument('Document about dogs');
$doc2->id = 'doc2';
$doc2->embedding = $embedding2;
$doc3 = new NeuronDocument('Document about pets');
$doc3->id = 'doc3';
$doc3->embedding = $embedding3;
$store->addDocuments([$doc1, $doc2, $doc3]);
// Search with a vector similar to doc1
$queryEmbedding = array_fill(0, 128, 0.0);
$queryEmbedding[0] = 1.0;
$results = $store->similaritySearch($queryEmbedding);
$this->assertNotEmpty($results);
$resultsArray = is_array($results) ? $results : iterator_to_array($results);
$this->assertCount(3, $resultsArray);
// First result should be doc1 (most similar)
$firstResult = $resultsArray[0];
$this->assertInstanceOf(NeuronDocument::class, $firstResult);
$this->assertEquals('doc1', $firstResult->id);
$this->assertGreaterThan(0, $firstResult->score);
}
public function testSimilaritySearchRespectsTopK(): void
{
$store = new PHPVector($this->tempDir, topK: 2);
$documents = [
$this->createDocumentWithEmbedding('Document 1'),
$this->createDocumentWithEmbedding('Document 2'),
$this->createDocumentWithEmbedding('Document 3'),
$this->createDocumentWithEmbedding('Document 4'),
];
$store->addDocuments($documents);
$queryEmbedding = $this->createTestEmbedding();
$results = $store->similaritySearch($queryEmbedding);
$resultsArray = is_array($results) ? $results : iterator_to_array($results);
$this->assertCount(2, $resultsArray);
}
public function testDocumentMetadataIsPreserved(): void
{
$store = new PHPVector($this->tempDir);
$document = new NeuronDocument('Test content');
$document->embedding = $this->createTestEmbedding();
$document->metadata = ['key' => 'value', 'number' => 42];
$store->addDocument($document);
$queryEmbedding = $document->embedding;
$results = $store->similaritySearch($queryEmbedding);
$resultsArray = is_array($results) ? $results : iterator_to_array($results);
$firstResult = $resultsArray[0];
$this->assertEquals(['key' => 'value', 'number' => 42], $firstResult->metadata);
}
public function testDocumentContentIsPreserved(): void
{
$store = new PHPVector($this->tempDir);
$expectedContent = 'This is the document content to preserve';
$document = new NeuronDocument($expectedContent);
$document->embedding = $this->createTestEmbedding();
$store->addDocument($document);
$results = $store->similaritySearch($document->embedding);
$resultsArray = is_array($results) ? $results : iterator_to_array($results);
$this->assertEquals($expectedContent, $resultsArray[0]->content);
}
public function testAddDocumentReturnsAdapterInstance(): void
{
$store = new PHPVector($this->tempDir);
$document = new NeuronDocument('Test');
$document->embedding = $this->createTestEmbedding();
$result = $store->addDocument($document);
$this->assertSame($store, $result);
}
public function testAddDocumentsReturnsAdapterInstance(): void
{
$store = new PHPVector($this->tempDir);
$documents = [
$this->createDocumentWithEmbedding('Doc 1'),
$this->createDocumentWithEmbedding('Doc 2'),
];
$result = $store->addDocuments($documents);
$this->assertSame($store, $result);
}
public function testSourceTypeAndNameRoundTripWithoutLeakingIntoMetadata(): void
{
$store = new PHPVector($this->tempDir);
$document = new NeuronDocument('Round trip content');
$document->id = 'rt1';
$document->embedding = $this->createTestEmbedding();
$document->sourceType = 'pdf';
$document->sourceName = 'manual.pdf';
$document->metadata = ['author' => 'jane', 'pages' => 12, 'published' => true];
$store->addDocument($document);
$results = $store->similaritySearch($document->embedding);
$resultsArray = is_array($results) ? $results : iterator_to_array($results);
$first = $resultsArray[0];
self::assertSame('pdf', $first->sourceType);
self::assertSame('manual.pdf', $first->sourceName);
self::assertSame(['author' => 'jane', 'pages' => 12, 'published' => true], $first->metadata);
}
public function testMutationsPersistWhenAutoSaveEnabled(): void
{
$store = new PHPVector($this->tempDir);
$store->addDocuments([
$this->createDocumentWithEmbedding('Auto 1'),
$this->createDocumentWithEmbedding('Auto 2'),
]);
// No explicit save(): auto-save should have persisted the index.
$reopened = VectorDatabase::open($this->tempDir);
self::assertSame(2, $reopened->count());
}
public function testAutoSaveDisabledDoesNotPersistUntilManualSave(): void
{
$store = new PHPVector($this->tempDir, autoSave: false);
$store->addDocuments([
$this->createDocumentWithEmbedding('Manual 1'),
$this->createDocumentWithEmbedding('Manual 2'),
]);
// Index not yet persisted: meta.json must not exist on disk.
self::assertFileDoesNotExist($this->tempDir . '/meta.json');
$this->getDatabase($store)->save();
$afterSave = VectorDatabase::open($this->tempDir);
self::assertSame(2, $afterSave->count());
}
public function testDeleteByRemovesMatchingSourceType(): void
{
$store = new PHPVector($this->tempDir);
$store->addDocuments([
$this->makeSourcedDocument('a', 'pdf', 'one.pdf'),
$this->makeSourcedDocument('b', 'pdf', 'two.pdf'),
$this->makeSourcedDocument('c', 'web', 'site'),
]);
self::assertSame(3, $this->getDatabase($store)->count());
$store->deleteBy('pdf');
self::assertSame(1, $this->getDatabase($store)->count());
}
public function testDeleteByRemovesOnlyExactTypeAndName(): void
{
$store = new PHPVector($this->tempDir);
$store->addDocuments([
$this->makeSourcedDocument('a', 'pdf', 'one.pdf'),
$this->makeSourcedDocument('b', 'pdf', 'two.pdf'),
]);
$store->deleteBy('pdf', 'one.pdf');
self::assertSame(1, $this->getDatabase($store)->count());
}
public function testDeleteByWithNoMatchIsNoop(): void
{
$store = new PHPVector($this->tempDir);
$store->addDocument($this->makeSourcedDocument('a', 'pdf', 'one.pdf'));
$result = $store->deleteBy('missing');
self::assertSame(1, $this->getDatabase($store)->count());
self::assertSame($store, $result);
}
public function testDeleteBySourceDelegatesToDeleteBy(): void
{
$store = new PHPVector($this->tempDir);
$store->addDocuments([
$this->makeSourcedDocument('a', 'pdf', 'one.pdf'),
$this->makeSourcedDocument('b', 'web', 'site'),
]);
$store->deleteBySource('pdf', 'one.pdf');
self::assertSame(1, $this->getDatabase($store)->count());
}
public function testDeleteByPersistsWhenAutoSaveEnabled(): void
{
$store = new PHPVector($this->tempDir);
$store->addDocuments([
$this->makeSourcedDocument('a', 'pdf', 'one.pdf'),
$this->makeSourcedDocument('b', 'web', 'site'),
]);
$store->deleteBy('pdf');
$reopened = VectorDatabase::open($this->tempDir);
self::assertSame(1, $reopened->count());
}
private function createDocumentWithEmbedding(string $content): NeuronDocument
{
$document = new NeuronDocument($content);
$document->embedding = $this->createTestEmbedding();
return $document;
}
private function makeSourcedDocument(string $id, string $sourceType, string $sourceName): NeuronDocument
{
$document = new NeuronDocument('content ' . $id);
$document->id = $id;
$document->embedding = $this->createTestEmbedding();
$document->sourceType = $sourceType;
$document->sourceName = $sourceName;
return $document;
}
}