Repository navigation
Expand file tree
/
Copy pathtest_batch_processing.py
More file actions
574 lines (447 loc) · 21.2 KB
/
Copy pathtest_batch_processing.py
File metadata and controls
574 lines (447 loc) · 21.2 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# tests/test_batch_processing.py
import pytest
from unittest.mock import Mock, AsyncMock, patch, MagicMock
from langchain_core.documents import Document
class TestBatchProcessing:
"""Test batch processing functions."""
@pytest.fixture
def mock_documents(self):
"""Create mock documents for testing."""
return [
Document(page_content=f"content_{i}", metadata={"file_id": "test_file"})
for i in range(10)
]
@pytest.fixture
def mock_async_vector_store(self):
"""Create mock async vector store."""
store = AsyncMock()
store.aadd_documents = AsyncMock(return_value=["id1", "id2"])
store.delete = AsyncMock()
return store
@pytest.fixture
def mock_sync_vector_store(self):
"""Create mock sync vector store."""
store = Mock()
store.add_documents = Mock(return_value=["id1", "id2"])
store.delete = Mock()
return store
# --- Async Pipeline Tests ---
@pytest.mark.asyncio
async def test_async_pipeline_basic(self, mock_documents, mock_async_vector_store):
"""Test basic async pipeline processing."""
from app.routes.document_routes import _process_documents_async_pipeline
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
result = await _process_documents_async_pipeline(
documents=mock_documents,
file_id="test_file",
vector_store=mock_async_vector_store,
executor=None,
)
assert len(result) > 0
assert mock_async_vector_store.aadd_documents.called
@pytest.mark.asyncio
async def test_async_pipeline_single_batch(self, mock_async_vector_store):
"""Test when all documents fit in one batch."""
from app.routes.document_routes import _process_documents_async_pipeline
docs = [Document(page_content="test", metadata={})]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 10):
result = await _process_documents_async_pipeline(
documents=docs,
file_id="test_file",
vector_store=mock_async_vector_store,
executor=None,
)
assert mock_async_vector_store.aadd_documents.call_count == 1
@pytest.mark.asyncio
async def test_async_pipeline_exact_batch_size(self, mock_async_vector_store):
"""Test when document count equals batch size."""
from app.routes.document_routes import _process_documents_async_pipeline
docs = [Document(page_content=f"test_{i}", metadata={}) for i in range(5)]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 5):
result = await _process_documents_async_pipeline(
documents=docs,
file_id="test_file",
vector_store=mock_async_vector_store,
executor=None,
)
assert mock_async_vector_store.aadd_documents.call_count == 1
@pytest.mark.asyncio
async def test_async_pipeline_empty_documents(self, mock_async_vector_store):
"""Test with empty document list."""
from app.routes.document_routes import _process_documents_async_pipeline
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
result = await _process_documents_async_pipeline(
documents=[],
file_id="test_file",
vector_store=mock_async_vector_store,
executor=None,
)
assert result == []
assert not mock_async_vector_store.aadd_documents.called
@pytest.mark.asyncio
async def test_async_pipeline_rollback_on_error(
self, mock_documents, mock_async_vector_store
):
"""Test that rollback occurs when insertion fails after some success."""
from app.routes.document_routes import _process_documents_async_pipeline
# First batch succeeds, second batch fails
mock_async_vector_store.aadd_documents = AsyncMock(
side_effect=[["id1"], Exception("DB error")]
)
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
with pytest.raises(Exception, match="DB error"):
await _process_documents_async_pipeline(
documents=mock_documents,
file_id="test_file",
vector_store=mock_async_vector_store,
executor=None,
)
mock_async_vector_store.delete.assert_called_once()
@pytest.mark.asyncio
async def test_async_pipeline_no_rollback_on_first_batch_error(
self, mock_documents, mock_async_vector_store
):
"""Test that no rollback occurs if first batch fails (nothing inserted)."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_async_vector_store.aadd_documents = AsyncMock(
side_effect=Exception("DB error")
)
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
with pytest.raises(Exception):
await _process_documents_async_pipeline(
documents=mock_documents,
file_id="test_file",
vector_store=mock_async_vector_store,
executor=None,
)
# Should not attempt rollback since nothing was inserted
assert not mock_async_vector_store.delete.called
# --- Sync Batched Tests ---
@pytest.mark.asyncio
async def test_sync_batched_basic(self, mock_documents, mock_sync_vector_store):
"""Test basic sync batch processing."""
from app.routes.document_routes import _process_documents_batched_sync
import asyncio
# Create a real executor for the test
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
result = await _process_documents_batched_sync(
documents=mock_documents,
file_id="test_file",
vector_store=mock_sync_vector_store,
executor=executor,
)
assert len(result) > 0
assert mock_sync_vector_store.add_documents.called
@pytest.mark.asyncio
async def test_sync_batched_empty_documents(self, mock_sync_vector_store):
"""Test sync batch processing with empty documents."""
from app.routes.document_routes import _process_documents_batched_sync
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
result = await _process_documents_batched_sync(
documents=[],
file_id="test_file",
vector_store=mock_sync_vector_store,
executor=None,
)
assert result == []
assert not mock_sync_vector_store.add_documents.called
@pytest.mark.asyncio
async def test_sync_batched_rollback_on_error(
self, mock_documents, mock_sync_vector_store
):
"""Test sync rollback behavior."""
from app.routes.document_routes import _process_documents_batched_sync
from concurrent.futures import ThreadPoolExecutor
# First batch succeeds, second batch fails
mock_sync_vector_store.add_documents = Mock(
side_effect=[["id1"], Exception("DB error")]
)
with ThreadPoolExecutor(max_workers=2) as executor:
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
with pytest.raises(Exception):
await _process_documents_batched_sync(
documents=mock_documents,
file_id="test_file",
vector_store=mock_sync_vector_store,
executor=executor,
)
mock_sync_vector_store.delete.assert_called_once()
@pytest.mark.asyncio
async def test_sync_batched_no_rollback_on_first_error(
self, mock_documents, mock_sync_vector_store
):
"""Test that no rollback occurs if first batch fails."""
from app.routes.document_routes import _process_documents_batched_sync
from concurrent.futures import ThreadPoolExecutor
mock_sync_vector_store.add_documents = Mock(side_effect=Exception("DB error"))
with ThreadPoolExecutor(max_workers=2) as executor:
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 3):
with pytest.raises(Exception):
await _process_documents_batched_sync(
documents=mock_documents,
file_id="test_file",
vector_store=mock_sync_vector_store,
executor=executor,
)
# Should not attempt rollback since nothing was inserted
assert not mock_sync_vector_store.delete.called
class TestBatchConfiguration:
"""Test configuration and edge cases."""
def test_batch_calculation(self):
"""Test batch count calculation using the utility function."""
from app.routes.document_routes import calculate_num_batches
# 10 docs, batch size 3 = 4 batches (3+3+3+1)
assert calculate_num_batches(10, 3) == 4
# Exact division
assert calculate_num_batches(9, 3) == 3
# Single item
assert calculate_num_batches(1, 3) == 1
# Zero items
assert calculate_num_batches(0, 3) == 0
# Batch size larger than total
assert calculate_num_batches(5, 10) == 1
# Edge case: batch_size of 0 returns 1 (fallback)
assert calculate_num_batches(10, 0) == 1
# Edge case: batch_size of 1
assert calculate_num_batches(5, 1) == 5
def test_embedding_batch_size_from_env(self):
"""Test that EMBEDDING_BATCH_SIZE is read from environment variable."""
import os
from importlib import reload
# Save current value
original = os.environ.get("EMBEDDING_BATCH_SIZE")
try:
# Set a specific test value
os.environ["EMBEDDING_BATCH_SIZE"] = "999"
import app.config as config_module
reload(config_module)
assert config_module.EMBEDDING_BATCH_SIZE == 999
finally:
# Restore original value
if original is not None:
os.environ["EMBEDDING_BATCH_SIZE"] = original
elif "EMBEDDING_BATCH_SIZE" in os.environ:
del os.environ["EMBEDDING_BATCH_SIZE"]
def test_embedding_max_queue_size_from_env(self):
"""Test that EMBEDDING_MAX_QUEUE_SIZE is read from environment variable."""
import os
from importlib import reload
original = os.environ.get("EMBEDDING_MAX_QUEUE_SIZE")
try:
os.environ["EMBEDDING_MAX_QUEUE_SIZE"] = "10"
import app.config as config_module
reload(config_module)
assert config_module.EMBEDDING_MAX_QUEUE_SIZE == 10
finally:
if original is not None:
os.environ["EMBEDDING_MAX_QUEUE_SIZE"] = original
elif "EMBEDDING_MAX_QUEUE_SIZE" in os.environ:
del os.environ["EMBEDDING_MAX_QUEUE_SIZE"]
class TestBatchSizeEdgeCases:
"""Test various batch size configurations."""
@pytest.mark.asyncio
@pytest.mark.parametrize(
"batch_size,doc_count,expected_batches",
[
(1, 5, 5), # Each doc separate
(5, 5, 1), # Exact fit
(10, 5, 1), # Batch larger than docs
(3, 10, 4), # Normal case
(100, 1, 1), # Large batch, single doc
],
)
async def test_batch_counts(self, batch_size, doc_count, expected_batches):
"""Test various batch size and document count combinations."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_store = AsyncMock()
mock_store.aadd_documents = AsyncMock(return_value=["id"])
docs = [
Document(page_content=f"doc_{i}", metadata={}) for i in range(doc_count)
]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", batch_size):
await _process_documents_async_pipeline(
documents=docs, file_id="test", vector_store=mock_store, executor=None
)
assert mock_store.aadd_documents.call_count == expected_batches
@pytest.mark.asyncio
async def test_large_batch_size_single_call(self):
"""Test that a very large batch size results in a single call."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_store = AsyncMock()
mock_store.aadd_documents = AsyncMock(return_value=["id"])
docs = [Document(page_content=f"doc_{i}", metadata={}) for i in range(100)]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 1000):
await _process_documents_async_pipeline(
documents=docs, file_id="test", vector_store=mock_store, executor=None
)
assert mock_store.aadd_documents.call_count == 1
@pytest.mark.asyncio
async def test_batch_size_one_multiple_calls(self):
"""Test that batch size of 1 results in many calls."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_store = AsyncMock()
mock_store.aadd_documents = AsyncMock(return_value=["id"])
docs = [Document(page_content=f"doc_{i}", metadata={}) for i in range(5)]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 1):
await _process_documents_async_pipeline(
documents=docs, file_id="test", vector_store=mock_store, executor=None
)
assert mock_store.aadd_documents.call_count == 5
class TestProducerConsumerPattern:
"""Test the producer-consumer pattern behavior."""
@pytest.mark.asyncio
async def test_producer_signals_completion_on_success(self):
"""Test that producer always signals completion."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_store = AsyncMock()
mock_store.aadd_documents = AsyncMock(return_value=["id"])
docs = [Document(page_content="test", metadata={})]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 1):
result = await _process_documents_async_pipeline(
documents=docs, file_id="test", vector_store=mock_store, executor=None
)
# If we get here without hanging, the producer signaled completion
assert result == ["id"]
@pytest.mark.asyncio
async def test_consumer_handles_exception_in_batch(self):
"""Test that consumer properly handles exceptions from vector store."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_store = AsyncMock()
mock_store.aadd_documents = AsyncMock(side_effect=ValueError("Test error"))
mock_store.delete = AsyncMock()
docs = [Document(page_content="test", metadata={})]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 1):
with pytest.raises(ValueError, match="Test error"):
await _process_documents_async_pipeline(
documents=docs,
file_id="test",
vector_store=mock_store,
executor=None,
)
@pytest.mark.asyncio
async def test_all_ids_collected_across_batches(self):
"""Test that IDs from all batches are collected."""
from app.routes.document_routes import _process_documents_async_pipeline
mock_store = AsyncMock()
# Return different IDs for each batch
mock_store.aadd_documents = AsyncMock(
side_effect=[["id1", "id2"], ["id3", "id4"], ["id5"]]
)
docs = [Document(page_content=f"doc_{i}", metadata={}) for i in range(5)]
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 2):
result = await _process_documents_async_pipeline(
documents=docs, file_id="test", vector_store=mock_store, executor=None
)
assert len(result) == 5
assert result == ["id1", "id2", "id3", "id4", "id5"]
class TestSyncBatchedMongoCompat:
"""Regression tests for MongoDB-compatible batch processing (PR #266)."""
@pytest.mark.asyncio
async def test_sync_batched_rejects_documents_keyword_with_legacy_store(self):
"""Regression: a store using 'docs' (not 'documents') as its param name must
still work, proving the call site uses positional — not keyword — dispatch."""
from app.routes.document_routes import _process_documents_batched_sync
from concurrent.futures import ThreadPoolExecutor
class LegacyMongoStore:
"""No **kwargs — documents= keyword would raise TypeError."""
def add_documents(self, docs, ids):
return [f"id_{i}" for i in range(len(docs))]
def delete(self, ids=None):
pass
docs = [
Document(page_content=f"content_{i}", metadata={"file_id": "test_file"})
for i in range(5)
]
with ThreadPoolExecutor(max_workers=1) as executor:
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 2):
result = await _process_documents_batched_sync(
documents=docs,
file_id="test_file",
vector_store=LegacyMongoStore(),
executor=executor,
)
assert len(result) == 5
@pytest.mark.asyncio
async def test_sync_batched_with_base_class_signature(self):
"""Positional dispatch also works with a store matching the VectorStore base class signature."""
from app.routes.document_routes import _process_documents_batched_sync
from concurrent.futures import ThreadPoolExecutor
class BaseClassStore:
def add_documents(self, documents, ids=None, **kwargs):
return [f"id_{i}" for i in range(len(documents))]
def delete(self, ids=None):
pass
docs = [
Document(page_content=f"content_{i}", metadata={"file_id": "test_file"})
for i in range(3)
]
with ThreadPoolExecutor(max_workers=1) as executor:
with patch("app.routes.document_routes.EMBEDDING_BATCH_SIZE", 2):
result = await _process_documents_batched_sync(
documents=docs,
file_id="test_file",
vector_store=BaseClassStore(),
executor=executor,
)
assert len(result) == 3
class TestMongoIdGeneration:
"""Test that digest-based ID generation produces unique IDs across batches."""
def test_unique_ids_across_batches(self):
"""Simulate multiple batch calls and verify no ID collisions."""
import hashlib
file_id = "test_file"
all_ids = []
for batch_idx in range(3):
batch_docs = [
Document(
page_content=f"content_{batch_idx * 3 + i}",
metadata={
"file_id": file_id,
"digest": hashlib.md5(
f"content_{batch_idx * 3 + i}".encode()
).hexdigest(),
},
)
for i in range(3)
]
f_ids = [
f"{file_id}_{doc.metadata.get('digest') or hashlib.md5(doc.page_content.encode()).hexdigest()}"
for doc in batch_docs
]
all_ids.extend(f_ids)
assert len(all_ids) == 9
assert len(set(all_ids)) == 9
def test_old_sequential_ids_would_collide(self):
"""Demonstrates the old per-batch range(len) approach caused ID collisions."""
file_id = "test_file"
all_ids = []
for _ in range(3):
batch_size = 3
old_ids = [f"{file_id}_{i}" for i in range(batch_size)]
all_ids.extend(old_ids)
assert len(all_ids) == 9
assert len(set(all_ids)) == 3
def test_fallback_to_content_hash_without_digest_metadata(self):
"""IDs are unique even when documents lack a 'digest' metadata field."""
import hashlib
file_id = "test_file"
docs = [
Document(page_content=f"content_{i}", metadata={"file_id": file_id})
for i in range(5)
]
f_ids = [
f"{file_id}_{doc.metadata.get('digest') or hashlib.md5(doc.page_content.encode()).hexdigest()}"
for doc in docs
]
assert len(set(f_ids)) == 5
def test_empty_documents_returns_empty(self):
"""AtlasMongoVector.add_documents with empty list returns empty."""
pytest.importorskip("langchain_mongodb", reason="requires langchain_mongodb")
from unittest.mock import MagicMock
from app.services.vector_store.atlas_mongo_vector import AtlasMongoVector
store = MagicMock(spec=AtlasMongoVector)
store.add_documents = AtlasMongoVector.add_documents.__get__(store)
result = store.add_documents([])
assert result == []