Archon/python/tests/test_document_storage_metrics.py
Wirasm 3e204b0be1
Fix race condition in concurrent crawling with unique source IDs (#472)
* Fix race condition in concurrent crawling with unique source IDs

- Add unique hash-based source_id generation to prevent conflicts
- Separate source identification from display with three fields:
  - source_id: 16-char SHA256 hash for unique identification
  - source_url: Original URL for tracking
  - source_display_name: Human-friendly name for UI
- Add comprehensive test suite validating the fix
- Migrate existing data with backward compatibility

* Fix title generation to use source_display_name for better AI context

- Pass source_display_name to title generation function
- Use display name in AI prompt instead of hash-based source_id
- Results in more specific, meaningful titles for each source

* Skip AI title generation when display name is available

- Use source_display_name directly as title to avoid unnecessary AI calls
- More efficient and predictable than AI-generated titles
- Keep AI generation only as fallback for backward compatibility

* Fix critical issues from code review

- Add missing os import to prevent NameError crash
- Remove unused imports (pytest, Mock, patch, hashlib, urlparse, etc.)
- Fix GitHub API capitalization consistency
- Reuse existing DocumentStorageService instance
- Update test expectations to match corrected capitalization

Addresses CodeRabbit review feedback on PR #472

* Add safety improvements from code review

- Truncate display names to 100 chars when used as titles
- Document hash collision probability (negligible for <1M sources)

Simple, pragmatic fixes per KISS principle

* Fix code extraction to use hash-based source_ids and improve display names

- Fixed critical bug where code extraction was using old domain-based source_ids
- Updated code extraction service to accept source_id as parameter instead of extracting from URL
- Added special handling for llms.txt and sitemap.xml files in display names
- Added comprehensive tests for source_id handling in code extraction
- Removed unused urlparse import from code_extraction_service.py

This fixes the foreign key constraint errors that were preventing code examples
from being stored after the source_id architecture refactor.

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix critical variable shadowing and source_type determination issues

- Fixed variable shadowing in document_storage_operations.py where source_url parameter
  was being overwritten by document URLs, causing incorrect source_url in database
- Fixed source_type determination to use actual URLs instead of hash-based source_id
- Added comprehensive tests for source URL preservation
- Ensure source_type is correctly set to "file" for file uploads, "url" for web crawls

The variable shadowing bug was causing sitemap sources to have the wrong source_url
(last crawled page instead of sitemap URL). The source_type bug would mark all
sources as "url" even for file uploads due to hash-based IDs not starting with "file_".

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix URL canonicalization and document metrics calculation

- Implement proper URL canonicalization to prevent duplicate sources
  - Remove trailing slashes (except root)
  - Remove URL fragments
  - Remove tracking parameters (utm_*, gclid, fbclid, etc.)
  - Sort query parameters for consistency
  - Remove default ports (80 for HTTP, 443 for HTTPS)
  - Normalize scheme and domain to lowercase

- Fix avg_chunks_per_doc calculation to avoid division by zero
  - Track processed_docs count separately from total crawl_results
  - Handle all-empty document sets gracefully
  - Show processed/total in logs for better visibility

- Add comprehensive tests for both fixes
  - 10 test cases for URL canonicalization edge cases
  - 4 test cases for document metrics calculation

This prevents database constraint violations when crawling the same
content with URL variations and provides accurate metrics in logs.

* Fix synchronous extract_source_summary blocking async event loop

- Run extract_source_summary in thread pool using asyncio.to_thread
- Prevents blocking the async event loop during AI summary generation
- Preserves exact error handling and fallback behavior
- Variables (source_id, combined_content) properly passed to thread

Added comprehensive tests verifying:
- Function runs in thread without blocking
- Error handling works correctly with fallback
- Multiple sources can be processed
- Thread safety with variable passing

* Fix synchronous update_source_info blocking async event loop

- Run update_source_info in thread pool using asyncio.to_thread
- Prevents blocking the async event loop during database operations
- Preserves exact error handling and fallback behavior
- All kwargs properly passed to thread execution

Added comprehensive tests verifying:
- Function runs in thread without blocking
- Error handling triggers fallback correctly
- All kwargs are preserved when passed to thread
- Existing extract_source_summary tests still pass

* Fix race condition in source creation using upsert

- Replace INSERT with UPSERT for new sources to prevent PRIMARY KEY violations
- Handles concurrent crawls attempting to create the same source
- Maintains existing UPDATE behavior for sources that already exist

Added comprehensive tests verifying:
- Concurrent source creation doesn't fail
- Upsert is used for new sources (not insert)
- Update is still used for existing sources
- Async concurrent operations work correctly
- Race conditions with delays are handled

This prevents database constraint errors when multiple crawls target
the same URL simultaneously.

* Add migration detection UI components

Add MigrationBanner component with clear user instructions for database schema updates. Add useMigrationStatus hook for periodic health check monitoring with graceful error handling.

* Integrate migration banner into main app

Add migration status monitoring and banner display to App.tsx. Shows migration banner when database schema updates are required.

* Enhance backend startup error instructions

Add detailed Docker restart instructions and migration script guidance. Improves user experience when encountering startup failures.

* Add database schema caching to health endpoint

Implement smart caching for schema validation to prevent repeated database queries. Cache successful validations permanently and throttle failures to 30-second intervals. Replace debug prints with proper logging.

* Clean up knowledge API imports and logging

Remove duplicate import statements and redundant logging. Improves code clarity and reduces log noise.

* Remove unused instructions prop from MigrationBanner

Clean up component API by removing instructions prop that was accepted but never rendered. Simplifies the interface and eliminates dead code while keeping the functional hardcoded migration steps.

* Add schema_valid flag to migration_required health response

Add schema_valid: false flag to health endpoint response when database schema migration is required. Improves API consistency without changing existing behavior.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-29 14:54:16 +03:00

205 lines
9.5 KiB
Python

"""
Test document storage metrics calculation.
This test ensures that avg_chunks_per_doc is calculated correctly
and handles edge cases like empty documents.
"""
import pytest
from unittest.mock import Mock, AsyncMock, patch
from src.server.services.crawling.document_storage_operations import DocumentStorageOperations
class TestDocumentStorageMetrics:
"""Test metrics calculation in document storage operations."""
@pytest.mark.asyncio
async def test_avg_chunks_calculation_with_empty_docs(self):
"""Test that avg_chunks_per_doc handles empty documents correctly."""
# Create mock supabase client
mock_supabase = Mock()
doc_storage = DocumentStorageOperations(mock_supabase)
# Mock the storage service
doc_storage.doc_storage_service.smart_chunk_text = Mock(
side_effect=lambda text, chunk_size: ["chunk1", "chunk2"] if text else []
)
# Mock internal methods
doc_storage._create_source_records = AsyncMock()
# Track what gets logged
logged_messages = []
with patch('src.server.services.crawling.document_storage_operations.safe_logfire_info') as mock_log:
mock_log.side_effect = lambda msg: logged_messages.append(msg)
with patch('src.server.services.crawling.document_storage_operations.add_documents_to_supabase'):
# Test data with mix of empty and non-empty documents
crawl_results = [
{"url": "https://example.com/page1", "markdown": "Content 1"},
{"url": "https://example.com/page2", "markdown": ""}, # Empty
{"url": "https://example.com/page3", "markdown": "Content 3"},
{"url": "https://example.com/page4", "markdown": ""}, # Empty
{"url": "https://example.com/page5", "markdown": "Content 5"},
]
result = await doc_storage.process_and_store_documents(
crawl_results=crawl_results,
request={},
crawl_type="test",
original_source_id="test123",
source_url="https://example.com",
source_display_name="Example"
)
# Find the metrics log message
metrics_log = None
for msg in logged_messages:
if "Document storage | processed=" in msg:
metrics_log = msg
break
assert metrics_log is not None, "Should log metrics"
# Verify metrics are correct
# 3 documents processed (non-empty), 5 total, 6 chunks (2 per doc), avg = 2.0
assert "processed=3/5" in metrics_log, "Should show 3 processed out of 5 total"
assert "chunks=6" in metrics_log, "Should have 6 chunks total"
assert "avg_chunks_per_doc=2.0" in metrics_log, "Average should be 2.0 (6/3)"
@pytest.mark.asyncio
async def test_avg_chunks_all_empty_docs(self):
"""Test that avg_chunks_per_doc handles all empty documents without division by zero."""
mock_supabase = Mock()
doc_storage = DocumentStorageOperations(mock_supabase)
# Mock the storage service
doc_storage.doc_storage_service.smart_chunk_text = Mock(return_value=[])
doc_storage._create_source_records = AsyncMock()
logged_messages = []
with patch('src.server.services.crawling.document_storage_operations.safe_logfire_info') as mock_log:
mock_log.side_effect = lambda msg: logged_messages.append(msg)
with patch('src.server.services.crawling.document_storage_operations.add_documents_to_supabase'):
# All documents are empty
crawl_results = [
{"url": "https://example.com/page1", "markdown": ""},
{"url": "https://example.com/page2", "markdown": ""},
{"url": "https://example.com/page3", "markdown": ""},
]
result = await doc_storage.process_and_store_documents(
crawl_results=crawl_results,
request={},
crawl_type="test",
original_source_id="test456",
source_url="https://example.com",
source_display_name="Example"
)
# Find the metrics log
metrics_log = None
for msg in logged_messages:
if "Document storage | processed=" in msg:
metrics_log = msg
break
assert metrics_log is not None, "Should log metrics even with no processed docs"
# Should show 0 processed, 0 chunks, 0.0 average (no division by zero)
assert "processed=0/3" in metrics_log, "Should show 0 processed out of 3 total"
assert "chunks=0" in metrics_log, "Should have 0 chunks"
assert "avg_chunks_per_doc=0.0" in metrics_log, "Average should be 0.0 (no division by zero)"
@pytest.mark.asyncio
async def test_avg_chunks_single_doc(self):
"""Test avg_chunks_per_doc with a single document."""
mock_supabase = Mock()
doc_storage = DocumentStorageOperations(mock_supabase)
# Mock to return 5 chunks for content
doc_storage.doc_storage_service.smart_chunk_text = Mock(
return_value=["chunk1", "chunk2", "chunk3", "chunk4", "chunk5"]
)
doc_storage._create_source_records = AsyncMock()
logged_messages = []
with patch('src.server.services.crawling.document_storage_operations.safe_logfire_info') as mock_log:
mock_log.side_effect = lambda msg: logged_messages.append(msg)
with patch('src.server.services.crawling.document_storage_operations.add_documents_to_supabase'):
crawl_results = [
{"url": "https://example.com/page", "markdown": "Long content here..."},
]
result = await doc_storage.process_and_store_documents(
crawl_results=crawl_results,
request={},
crawl_type="test",
original_source_id="test789",
source_url="https://example.com",
source_display_name="Example"
)
# Find metrics log
metrics_log = None
for msg in logged_messages:
if "Document storage | processed=" in msg:
metrics_log = msg
break
assert metrics_log is not None
assert "processed=1/1" in metrics_log, "Should show 1 processed out of 1 total"
assert "chunks=5" in metrics_log, "Should have 5 chunks"
assert "avg_chunks_per_doc=5.0" in metrics_log, "Average should be 5.0"
@pytest.mark.asyncio
async def test_processed_count_accuracy(self):
"""Test that processed_docs count is accurate."""
mock_supabase = Mock()
doc_storage = DocumentStorageOperations(mock_supabase)
# Track which documents are chunked
chunked_urls = []
def mock_chunk(text, chunk_size):
if text:
return ["chunk"]
return []
doc_storage.doc_storage_service.smart_chunk_text = Mock(side_effect=mock_chunk)
doc_storage._create_source_records = AsyncMock()
with patch('src.server.services.crawling.document_storage_operations.safe_logfire_info'):
with patch('src.server.services.crawling.document_storage_operations.add_documents_to_supabase'):
# Mix of documents with various content states
crawl_results = [
{"url": "https://example.com/1", "markdown": "Content"},
{"url": "https://example.com/2", "markdown": ""}, # Empty markdown
{"url": "https://example.com/3", "markdown": None}, # None markdown
{"url": "https://example.com/4", "markdown": "More content"},
{"url": "https://example.com/5"}, # Missing markdown key
{"url": "https://example.com/6", "markdown": " "}, # Whitespace (counts as content)
]
result = await doc_storage.process_and_store_documents(
crawl_results=crawl_results,
request={},
crawl_type="test",
original_source_id="test999",
source_url="https://example.com",
source_display_name="Example"
)
# Should process documents 1, 4, and 6 (has content including whitespace)
assert result["chunk_count"] == 3, "Should have 3 chunks (one per processed doc)"
# Check url_to_full_document only has processed docs
assert len(result["url_to_full_document"]) == 3
assert "https://example.com/1" in result["url_to_full_document"]
assert "https://example.com/4" in result["url_to_full_document"]
assert "https://example.com/6" in result["url_to_full_document"]