"""Real PostgreSQL: failed final embedding batch has no publication effects.""" from concurrent.futures import ThreadPoolExecutor from uuid import uuid4 import pytest from sqlalchemy import text from app.infrastructure.file_store import LocalFileStore from app.infrastructure.intake_repository import SqlIntakeRepository from app.modules.documents.embeddings import EmbeddingLimits, EmbeddingProviderError, stage_document from app.modules.documents.intake import import_document, status from app.modules.documents.types import ChunkDraft from tests.unit.test_phase4 import FakeProvider def test_concurrent_final_batch_failures_preserve_zero_chunks(migrated_db, settings, tmp_path): engine, _ = migrated_db organization, administrator = uuid4(), uuid4() with engine.begin() as conn: conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'phase4')"), {"id": organization}) conn.execute(text("""INSERT INTO users(id,organization_id,username,password_hash,role) VALUES (:id,:org,:name,'fixture-only','admin')"""), dict(id=administrator, org=organization, name=str(administrator))) settings = settings.model_copy(update={"embedding_limits": EmbeddingLimits( unit="utf8_bytes", max_input_units=100, max_batch_units=200, max_batch_inputs=2)}) store = LocalFileStore(tmp_path / "originals") source = tmp_path / "sample.md" source.write_text("immutable evidence", encoding="utf-8") repository = SqlIntakeRepository(engine) document = import_document(repository, store, settings, path=source, administrator_id=administrator, request_id=uuid4())["document"] before = status(repository, administrator_id=administrator, document_id=document["id"]) def process(_): provider = FakeProvider(settings, fail_at=2) # The application has no engine/connection dependency. with pytest.raises(EmbeddingProviderError): with stage_document(provider, document_id=document["id"], chunks=[ChunkDraft(i, "a") for i in range(3)], processing_profile=document["processing_profile"]): pytest.fail("Incomplete staged document escaped") assert len(provider.calls) == 2 with ThreadPoolExecutor(max_workers=2) as pool: list(pool.map(process, range(2))) assert status(repository, administrator_id=administrator, document_id=document["id"]) == before assert store.read(document["storage_key"]) == source.read_bytes() with engine.connect() as conn: assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 @pytest.mark.parametrize("scale", [1e-30, 1e20]) def test_pgvector_unsafe_cosine_norm_is_rejected(migrated_db, scale): import math from app.modules.documents.embeddings import EmbeddingError, packed_vector engine, _ = migrated_db vector = [scale, 0, 0] value = "[" + ",".join(map(str, vector)) + "]" with engine.connect() as conn: distance = conn.execute(text("SELECT CAST(:value AS vector) <=> CAST(:value AS vector)"), {"value": value}).scalar_one() assert not math.isfinite(distance) with pytest.raises(EmbeddingError): packed_vector(vector, 3) def test_pgvector_distorted_subnormal_vector_is_rejected(migrated_db): """pgvector cosine distance suffers ~20% distortion on [3e-23,0,0] vs [1,0,0], rejected by application.""" from app.modules.documents.embeddings import EmbeddingError, packed_vector engine, _ = migrated_db with engine.connect() as conn: distance = conn.execute( text("SELECT CAST(:a AS vector) <=> CAST(:b AS vector)"), {"a": "[3e-23,0,0]", "b": "[1,0,0]"}, ).scalar_one() # High-precision theoretical distance is 0.0 (same direction), but pgvector gives ~0.1986 assert abs(distance - 0.198588) < 0.01 with pytest.raises(EmbeddingError): packed_vector([3e-23, 0, 0], 3) with pytest.raises(EmbeddingError): packed_vector([1e-21] * 16000, 16000) def test_accepted_packed_vectors_have_valid_pgvector_cosine_distances(migrated_db): from array import array import math from app.modules.documents.embeddings import packed_vector engine, _ = migrated_db vectors = [ [1, 0, 0], [-1, 0, 0], [0, 1, 0], [1e-18, 0, 0], [-1e-18, 0, 0], [1e18, 0, 0], [-1e18, 0, 0], [1e-30, 1, 0], [1e19, 1e19, 1e19], ] packed = [] for vector in vectors: value = array("f") value.frombytes(packed_vector(vector, 3)) packed.append(tuple(value)) with engine.connect() as conn: for left in packed: for right in packed: result = conn.execute(text("SELECT CAST(:left AS vector) <=> CAST(:right AS vector)"), { "left": "[" + ",".join(map(str, left)) + "]", "right": "[" + ",".join(map(str, right)) + "]", }).scalar_one() expected = 1 - sum(a * b for a, b in zip(left, right)) / ( math.sqrt(sum(a * a for a in left)) * math.sqrt(sum(b * b for b in right))) assert math.isfinite(result) and 0 <= result <= 2 assert result == pytest.approx(expected, abs=1e-6) assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 @pytest.mark.parametrize("dim,vectors", [ (1, [[1.0], [-1.0], [1e-18], [1e18]]), (2, [[1.0, 0.0], [0.0, -1.0], [-1e-18, 1e-18], [1e18, 1e18]]), (4, [ [1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0], [1e-18, 1e-18, 1e-18, 1e-18], [-1e18, -1e18, -1e18, -1e18], [1e-30, 1.0, 0.0, 0.0], ]), ]) def test_pgvector_cosine_references_across_dimensions_magnitudes_signs(migrated_db, dim, vectors): from array import array import math from app.modules.documents.embeddings import packed_vector engine, _ = migrated_db packed = [] for vector in vectors: val = array("f") val.frombytes(packed_vector(vector, dim)) packed.append(tuple(val)) with engine.connect() as conn: for left in packed: for right in packed: result = conn.execute(text("SELECT CAST(:left AS vector) <=> CAST(:right AS vector)"), { "left": "[" + ",".join(map(str, left)) + "]", "right": "[" + ",".join(map(str, right)) + "]", }).scalar_one() dot = sum(a * b for a, b in zip(left, right)) norm_a = math.sqrt(sum(a * a for a in left)) norm_b = math.sqrt(sum(b * b for b in right)) expected = 1.0 - (dot / (norm_a * norm_b)) assert math.isfinite(result) and 0 <= result <= 2 assert result == pytest.approx(expected, abs=1e-5) assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 @pytest.mark.parametrize("field", ["text", "section"]) def test_postgres_nul_strings_rejected_before_provider(migrated_db, settings, field): import json from dataclasses import replace from sqlalchemy.exc import DBAPIError from app.modules.documents.embeddings import EmbeddingError from tests.unit.test_phase4 import profile from tests.unit.test_phase4_closure import vision_chunks engine, _ = migrated_db provider, frozen, document, chunks = vision_chunks(settings, "image\x00section") if field == "text": chunks = [replace(chunks[0], text="evidence\x00text", section="valid")] location = dict(page=chunks[0].page, section=chunks[0].section) raw = json.dumps(location if field == "section" else {"text": chunks[0].text}) with engine.connect() as conn: with pytest.raises(DBAPIError) as caught: conn.execute(text("SELECT CAST(:raw AS jsonb)"), {"raw": raw}) assert caught.value.orig.sqlstate == "22P05" with pytest.raises(EmbeddingError) as caught: with stage_document(provider, document_id=document, chunks=chunks, processing_profile=frozen): pytest.fail("Database-incompatible evidence escaped staging") assert not caught.value.retryable and not provider.calls with engine.connect() as conn: assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 def test_postgres_valid_unicode_staging_roundtrip(migrated_db, settings): import json from tests.unit.test_phase4 import profile engine, _ = migrated_db provider = FakeProvider(settings) evidence = "\u0645\u062a\u0646\u200c \u0641\u0627\u0631\u0633\u06cc\r\n\u0634\u0631\u0627\u06cc\u0637" section = "\u0628\u062e\u0634\u200c\n\u06cc\u06a9" with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, evidence, section=section)], processing_profile=profile(settings, provider)) as staged: retained = staged.chunks[0] location = dict(page=retained.page, section=retained.section) with engine.connect() as conn: row = conn.execute(text("SELECT CAST(:evidence AS text), CAST(:location AS jsonb)"), dict(evidence=retained.text, location=json.dumps(location))).one() assert row[0] == evidence and row[1] == location assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 assert staged.closed def test_postgres_token_count_range_rejected_before_provider(migrated_db, settings): from types import SimpleNamespace from sqlalchemy.exc import DBAPIError from app.modules.documents.embeddings import EmbeddingError from tests.unit.test_phase4 import profile engine, _ = migrated_db with engine.connect() as conn: with pytest.raises(DBAPIError) as caught: conn.execute(text("SELECT CAST(:count AS integer)"), {"count": 2**31}) assert caught.value.orig.sqlstate == "22003" provider = FakeProvider(settings) counter = SimpleNamespace(identity="fake:closure", count=lambda text: 2**31) provider.request_policy["limits"] = EmbeddingLimits(unit="tokens", max_input_units=2**31, max_batch_units=2**31, max_batch_inputs=2, tokenizer=counter.identity).model_dump() with pytest.raises(EmbeddingError): with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=profile(settings, provider), token_counter=counter): pytest.fail("Database-incompatible token count escaped") assert not provider.calls with engine.connect() as conn: assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0