feat(ingestion): implement Phase 4 chunking and vector embedding generation
- Add heading and paragraph-preserving chunking algorithms with bounded overlap - Implement OpenAI embeddings client adapter with explicit token limits and batching - Implement stage_document pipeline with strict operational limits and memory protections - Add unit and integration tests covering chunking boundaries, timeouts, and vector generation
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
"""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
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Deterministic provider for database acceptance; no network or tokenizer."""
|
||||
import hashlib
|
||||
|
||||
from app.modules.documents.embeddings import EmbeddingProviderError
|
||||
|
||||
|
||||
class DeterministicEmbeddings:
|
||||
def __init__(self, settings, *, observe=None, fail_at=None):
|
||||
self.profile = settings.embedding_profile
|
||||
self.request_policy = settings.processing_profile()["embedding_request"]
|
||||
self.calls = []
|
||||
self.observe, self.fail_at = observe, fail_at
|
||||
|
||||
@staticmethod
|
||||
def vector(value):
|
||||
digest = hashlib.sha256(value.encode("utf-8")).digest()
|
||||
return [float(1 + digest[i]) for i in range(3)]
|
||||
|
||||
def embed(self, texts):
|
||||
self.calls.append(tuple(texts))
|
||||
if self.observe:
|
||||
self.observe(len(self.calls))
|
||||
if len(self.calls) == self.fail_at:
|
||||
raise EmbeddingProviderError("injected secret provider payload", retryable=False)
|
||||
return [self.vector(value) for value in texts]
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Fake HTTP only; never contact a real embedding provider."""
|
||||
from dataclasses import asdict, replace
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
from threading import Event
|
||||
from urllib.error import HTTPError, URLError
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings
|
||||
from app.modules.documents.embeddings import (
|
||||
EmbeddingError, EmbeddingProviderError, EmbeddingLimits, stage_document,
|
||||
)
|
||||
from app.modules.documents.types import ChunkDraft
|
||||
|
||||
|
||||
def adapter(settings, **kwargs):
|
||||
defaults = dict(profile=settings.embedding_profile, api_key="private-secret",
|
||||
limits=dict(unit="utf8_bytes", max_input_units=100,
|
||||
max_batch_units=200, max_batch_inputs=2))
|
||||
defaults.update(kwargs)
|
||||
return OpenAICompatibleEmbeddings(**defaults)
|
||||
|
||||
|
||||
def response(model="deterministic-test", data=None):
|
||||
return json.dumps(dict(model=model, data=data if data is not None else [
|
||||
dict(index=1, embedding=[0, 1, 0]), dict(index=0, embedding=[1, 0, 0])])).encode()
|
||||
|
||||
|
||||
def fake_http(monkeypatch, payload=None, error=None):
|
||||
requests = []
|
||||
class Opener:
|
||||
def open(self, request, timeout):
|
||||
requests.append(request)
|
||||
if error is not None:
|
||||
raise error
|
||||
return BytesIO(payload)
|
||||
monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener())
|
||||
return requests
|
||||
|
||||
|
||||
def profile(settings, provider, **limits):
|
||||
value = settings.processing_profile()
|
||||
value["embedding_request"] = provider.request_policy
|
||||
value["limits"].update(limits)
|
||||
return value
|
||||
|
||||
|
||||
def test_shuffled_indexes_optional_dimensions_and_secret(settings, monkeypatch):
|
||||
requests = fake_http(monkeypatch, response())
|
||||
provider = adapter(settings)
|
||||
assert provider.embed(["a", "b"]) == ((1, 0, 0), (0, 1, 0))
|
||||
assert "dimensions" not in json.loads(requests[0].data)
|
||||
assert json.loads(requests[0].data)["input"] == ["a", "b"]
|
||||
assert requests[0].full_url == "https://test.invalid/v1/embeddings"
|
||||
assert "private-secret" not in repr(provider)
|
||||
provider = adapter(settings, send_dimensions=True)
|
||||
provider.embed(["a", "b"])
|
||||
assert json.loads(requests[1].data)["dimensions"] == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [
|
||||
[dict(index=0, embedding=[1, 0, 0])],
|
||||
[dict(index=0, embedding=[1, 0, 0]), dict(index=0, embedding=[0, 1, 0])],
|
||||
[dict(index=-1, embedding=[1, 0, 0]), dict(index=1, embedding=[0, 1, 0])],
|
||||
[dict(index=True, embedding=[1, 0, 0]), dict(index=0, embedding=[0, 1, 0])],
|
||||
[dict(index=2, embedding=[1, 0, 0]), dict(index=0, embedding=[0, 1, 0])],
|
||||
[dict(index=0, embedding=[1, 0]), dict(index=1, embedding=[0, 1, 0])],
|
||||
*[[dict(index=0, embedding=[v, 0, 0]), dict(index=1, embedding=[0, 1, 0])]
|
||||
for v in (float("nan"), float("inf"), -float("inf"), 0, 1e100, 1e-100, True, "1")],
|
||||
])
|
||||
def test_bad_response_rejected(settings, monkeypatch, data):
|
||||
fake_http(monkeypatch, response(data=data))
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings).embed(["a", "b"])
|
||||
assert not caught.value.retryable
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [b"garbage", b"null", b"{}", response(model="other")])
|
||||
def test_bad_envelope(settings, monkeypatch, payload):
|
||||
fake_http(monkeypatch, payload)
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings).embed(["a", "b"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code,retryable", [(408, True), (429, True), (500, True), (503, True),
|
||||
(400, False), (401, False), (403, False), (404, False), (302, False)])
|
||||
def test_http_errors_once_redacted_and_closed(settings, monkeypatch, code, retryable):
|
||||
stream = BytesIO(b"private-secret provider details")
|
||||
error = HTTPError("https://secret.invalid", code, "private-secret", {}, stream)
|
||||
requests = fake_http(monkeypatch, error=error)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value.retryable == retryable
|
||||
assert "private-secret" not in str(caught.value)
|
||||
assert len(requests) == 1 and stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [TimeoutError("private-secret"), URLError("private-secret"), OSError("private-secret")])
|
||||
def test_network_errors(settings, monkeypatch, error):
|
||||
requests = fake_http(monkeypatch, error=error)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value.retryable and len(requests) == 1
|
||||
assert "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
def test_absolute_deadline_late_result_and_shared_capacity(settings, monkeypatch):
|
||||
entered, release, closed = Event(), Event(), Event()
|
||||
class Slow(BytesIO):
|
||||
def read(self, size):
|
||||
entered.set()
|
||||
release.wait(3)
|
||||
return super().read(size)
|
||||
def close(self):
|
||||
super().close()
|
||||
closed.set()
|
||||
class Opener:
|
||||
def open(self, *args, **kwargs):
|
||||
return Slow(response(data=[dict(index=0, embedding=[1, 0, 0])]))
|
||||
monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener())
|
||||
try:
|
||||
with pytest.raises(EmbeddingProviderError, match="deadline"):
|
||||
adapter(settings, timeout_seconds=.3).embed(["a"])
|
||||
assert entered.is_set()
|
||||
with pytest.raises(EmbeddingProviderError, match="capacity"):
|
||||
adapter(settings).embed(["a"])
|
||||
finally:
|
||||
release.set()
|
||||
assert closed.wait(2)
|
||||
# Synchronize release of capacity by joining the actual thread.
|
||||
import threading
|
||||
for thread in threading.enumerate():
|
||||
if thread.name == "embedding-request":
|
||||
thread.join(2)
|
||||
|
||||
|
||||
def test_response_size(settings, monkeypatch):
|
||||
fake_http(monkeypatch, b"x" * 101)
|
||||
with pytest.raises(EmbeddingError, match="byte limit"):
|
||||
adapter(settings, max_response_bytes=100).embed(["a"])
|
||||
|
||||
|
||||
class Counter:
|
||||
identity = "fake:compatible"
|
||||
def count(self, text):
|
||||
return 3 if text == "a" else 6
|
||||
|
||||
|
||||
def test_token_limits_require_compatible_counter(settings):
|
||||
limits = dict(unit="tokens", max_input_units=5, max_batch_units=5,
|
||||
max_batch_inputs=2, tokenizer=Counter.identity)
|
||||
with pytest.raises(EmbeddingError, match="counter"):
|
||||
adapter(settings, limits=limits)
|
||||
provider = adapter(settings, limits=limits, token_counter=Counter())
|
||||
with pytest.raises(EmbeddingError, match="input limit"):
|
||||
provider.embed(["b"])
|
||||
with pytest.raises(EmbeddingError, match="batch unit"):
|
||||
provider.embed(["a", "a"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("texts", [[], ["a", "b", "c"], ["x" * 101], [" "], ["é" * 51]])
|
||||
def test_input_and_byte_limits_before_request(settings, texts):
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings).embed(texts)
|
||||
|
||||
|
||||
def test_limits_configuration():
|
||||
with pytest.raises(ValueError):
|
||||
EmbeddingLimits(unit="tokens", max_input_units=5, max_batch_units=10, max_batch_inputs=2)
|
||||
with pytest.raises(ValueError):
|
||||
EmbeddingLimits(unit="utf8_bytes", max_input_units=5, max_batch_units=4, max_batch_inputs=2)
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def __init__(self, settings, fail_at=None, vectors=None):
|
||||
self.profile = settings.embedding_profile
|
||||
self.request_policy = adapter(settings).request_policy
|
||||
self.calls = []
|
||||
self.fail_at = fail_at
|
||||
self.vectors = vectors
|
||||
def embed(self, texts):
|
||||
self.calls.append(tuple(texts))
|
||||
if len(self.calls) == self.fail_at:
|
||||
raise EmbeddingProviderError("batch failed", retryable=True)
|
||||
return self.vectors if self.vectors is not None else [[1, 0, 0] for _ in texts]
|
||||
|
||||
|
||||
def test_complete_staging_and_release(settings):
|
||||
provider = FakeProvider(settings)
|
||||
chunks = [ChunkDraft(i, "a") for i in range(3)]
|
||||
frozen = profile(settings, provider)
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen) as staged:
|
||||
assert len(staged.chunks) == len(staged.vectors) == 3
|
||||
assert tuple(staged.vectors[0]) == (1, 0, 0)
|
||||
assert staged.processing_profile == frozen
|
||||
assert provider.calls == [("a", "a"), ("a",)]
|
||||
copy = staged.processing_profile
|
||||
copy["embedding"]["model"] = "evil"
|
||||
assert staged.processing_profile == frozen
|
||||
assert staged.closed
|
||||
with pytest.raises(ValueError):
|
||||
_ = staged.vectors
|
||||
|
||||
|
||||
def test_consumer_failure_releases_staging(settings):
|
||||
provider = FakeProvider(settings)
|
||||
with pytest.raises(RuntimeError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")],
|
||||
processing_profile=profile(settings, provider)) as staged:
|
||||
raise RuntimeError()
|
||||
assert staged.closed
|
||||
|
||||
|
||||
def test_failed_final_batch_never_yields(settings):
|
||||
provider = FakeProvider(settings, fail_at=2)
|
||||
with pytest.raises(EmbeddingProviderError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, "a") for i in range(3)],
|
||||
processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Incomplete staging became publishable")
|
||||
assert len(provider.calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunks", [
|
||||
[], [ChunkDraft(1, "a")], [ChunkDraft(0, "a"), ChunkDraft(0, "a")],
|
||||
[ChunkDraft(0, "a", page=0)], [ChunkDraft(0, "a", token_count=2)],
|
||||
[ChunkDraft(0, " ")],
|
||||
])
|
||||
def test_invalid_drafts(settings, chunks):
|
||||
provider = FakeProvider(settings)
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Bad draft became publishable")
|
||||
assert not provider.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vectors", [[], [[0, 0, 0]], [[float("nan"), 0, 0]], [[1, 0]]])
|
||||
def test_provider_neutral_validation(settings, vectors):
|
||||
provider = FakeProvider(settings, vectors=vectors)
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")],
|
||||
processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Bad vectors became publishable")
|
||||
|
||||
|
||||
def test_budget_exact_boundary_and_no_calls_on_overflow(settings):
|
||||
provider = FakeProvider(settings)
|
||||
frozen = profile(settings, provider)
|
||||
chunks = [ChunkDraft(0, "a", section="large metadata")]
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen) as staged:
|
||||
used = staged.payload_bytes
|
||||
# Profile itself includes the budget; choose equal digit lengths.
|
||||
frozen["limits"]["max_staged_bytes"] = 10000
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen) as staged:
|
||||
used = staged.payload_bytes
|
||||
# Replacing 10000 with smaller values changes profile byte length by one.
|
||||
frozen["limits"]["max_staged_bytes"] = used - 1
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen):
|
||||
pass
|
||||
frozen["limits"]["max_staged_bytes"] -= 1
|
||||
provider.calls.clear()
|
||||
with pytest.raises(EmbeddingError, match="memory budget"):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen):
|
||||
pytest.fail("Budget overflow yielded")
|
||||
assert not provider.calls
|
||||
|
||||
|
||||
def test_frozen_identity_policy_and_chunk_limit(settings):
|
||||
provider = FakeProvider(settings)
|
||||
for key in ("embedding", "embedding_request"):
|
||||
frozen = profile(settings, provider)
|
||||
frozen.pop(key)
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen):
|
||||
pytest.fail("Missing frozen profile yielded")
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, "a") for i in range(2)],
|
||||
processing_profile=profile(settings, provider, max_chunks=1)):
|
||||
pytest.fail("Too many chunks yielded")
|
||||
|
||||
|
||||
def test_token_staging_batch_partition_and_counts(settings):
|
||||
provider = FakeProvider(settings)
|
||||
limits = dict(unit="tokens", max_input_units=6, max_batch_units=6,
|
||||
max_batch_inputs=2, tokenizer=Counter.identity)
|
||||
provider.request_policy["limits"] = EmbeddingLimits(**limits).model_dump()
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, text) for i, text in enumerate(["a", "a", "b"])],
|
||||
processing_profile=profile(settings, provider), token_counter=Counter()) as staged:
|
||||
assert [c.token_count for c in staged.chunks] == [3, 3, 6]
|
||||
assert provider.calls == [("a", "a"), ("b",)]
|
||||
|
||||
|
||||
def test_settings_snapshot_without_credentials(settings):
|
||||
configured = settings.model_copy(update={"embedding_limits": EmbeddingLimits(
|
||||
unit="utf8_bytes", max_input_units=100, max_batch_units=200, max_batch_inputs=2)})
|
||||
assert "embedding_request" in configured.processing_profile()
|
||||
assert "api_key" not in json.dumps(configured.processing_profile())
|
||||
|
||||
def test_normalized_input_preserves_faithful_chunk(settings):
|
||||
provider = FakeProvider(settings)
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a\r\nb")],
|
||||
processing_profile=profile(settings, provider)) as staged:
|
||||
assert staged.chunks[0].text == "a\r\nb"
|
||||
assert provider.calls == [("a\nb",)]
|
||||
assert staged.vectors[0].readonly
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["profile", "request_policy"])
|
||||
def test_provider_profile_cannot_change_between_batches(settings, change):
|
||||
provider = FakeProvider(settings)
|
||||
original = provider.embed
|
||||
def embed(texts):
|
||||
result = original(texts)
|
||||
if change == "profile":
|
||||
provider.profile = replace(provider.profile, model="other")
|
||||
else:
|
||||
provider.request_policy["timeout_seconds"] += 1
|
||||
return result
|
||||
provider.embed = embed
|
||||
with pytest.raises(EmbeddingError, match="changed"):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, "a") for i in range(3)],
|
||||
processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Changed profile escaped")
|
||||
|
||||
|
||||
def test_tiktoken_counter_uses_explicit_encoding_without_special_rejection(monkeypatch):
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from app.infrastructure.openai_embeddings import TiktokenCounter
|
||||
calls = []
|
||||
class Encoding:
|
||||
def encode(self, text, *, disallowed_special):
|
||||
calls.append((text, disallowed_special))
|
||||
return [1, 2, 3]
|
||||
def get_encoding(name):
|
||||
assert name == "explicit-encoding"
|
||||
return Encoding()
|
||||
monkeypatch.setitem(sys.modules, "tiktoken", SimpleNamespace(get_encoding=get_encoding))
|
||||
counter = TiktokenCounter("explicit-encoding")
|
||||
assert counter.identity == "tiktoken:explicit-encoding"
|
||||
assert counter.count("a") == 3
|
||||
assert calls == [("a", ())]
|
||||
|
||||
|
||||
def test_adapter_composition_requires_secret_and_explicit_limits(settings):
|
||||
from pydantic import SecretStr
|
||||
with pytest.raises(ValueError, match="API_KEY"):
|
||||
OpenAICompatibleEmbeddings.from_settings(settings)
|
||||
configured = settings.model_copy(update={"embedding_api_key": SecretStr("private-secret")})
|
||||
with pytest.raises(EmbeddingError, match="limits"):
|
||||
OpenAICompatibleEmbeddings.from_settings(configured)
|
||||
configured = configured.model_copy(update={"embedding_limits": EmbeddingLimits(
|
||||
unit="utf8_bytes", max_input_units=100, max_batch_units=200, max_batch_inputs=2)})
|
||||
provider = OpenAICompatibleEmbeddings.from_settings(configured)
|
||||
assert provider.request_policy == configured.processing_profile()["embedding_request"]
|
||||
assert "private-secret" not in json.dumps(configured.processing_profile())
|
||||
@@ -0,0 +1,471 @@
|
||||
"""Remaining Phase 4 closure defects; fake providers and local byte streams only."""
|
||||
from copy import deepcopy
|
||||
from dataclasses import replace
|
||||
from io import BytesIO
|
||||
import hashlib
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from urllib.error import HTTPError
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings
|
||||
from app.modules.documents.embeddings import EmbeddingError, EmbeddingProviderError, EmbeddingLimits, stage_document
|
||||
from app.modules.documents.types import ChunkDraft, EmbeddingProfile, ExtractedBlock, ExtractionEnvelope
|
||||
from app.modules.documents.chunking import chunk_extraction
|
||||
from app.modules.documents.extraction_artifacts import extraction_profile_digest, serialize_artifact, validate_artifact
|
||||
from tests.unit.test_phase4 import FakeProvider, adapter, fake_http, profile, response
|
||||
from tests.unit.test_phase4_repairs import real_response
|
||||
|
||||
|
||||
def drift(provider, kind):
|
||||
if kind == "model":
|
||||
provider.profile = replace(provider.profile, model="changed")
|
||||
elif kind == "dimension":
|
||||
provider.profile = replace(provider.profile, dimensions=4)
|
||||
else:
|
||||
provider.request_policy["timeout_seconds"] += 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("when", ["iterator", "counter"])
|
||||
@pytest.mark.parametrize("kind", ["model", "dimension", "policy"])
|
||||
def test_preparation_drift_has_no_provider_work(settings, when, kind):
|
||||
provider = FakeProvider(settings)
|
||||
counter = None
|
||||
chunks = [ChunkDraft(0, "a")]
|
||||
if when == "counter":
|
||||
class Counter:
|
||||
identity = "fake:closure"
|
||||
def count(self, text):
|
||||
drift(provider, kind)
|
||||
return 1
|
||||
counter = Counter()
|
||||
provider.request_policy["limits"] = EmbeddingLimits(unit="tokens", max_input_units=100,
|
||||
max_batch_units=200, max_batch_inputs=2, tokenizer=counter.identity).model_dump()
|
||||
else:
|
||||
def drafts():
|
||||
drift(provider, kind)
|
||||
yield ChunkDraft(0, "a")
|
||||
chunks = drafts()
|
||||
frozen = deepcopy(profile(settings, provider))
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks,
|
||||
processing_profile=frozen, token_counter=counter):
|
||||
pytest.fail("Preparation drift yielded inconsistent staging")
|
||||
assert not caught.value.retryable and not provider.calls
|
||||
|
||||
|
||||
def test_iterator_exhaustion_drift_is_preflight(settings):
|
||||
provider = FakeProvider(settings)
|
||||
def drafts():
|
||||
yield ChunkDraft(0, "a")
|
||||
drift(provider, "model")
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=drafts(),
|
||||
processing_profile=deepcopy(profile(settings, provider))):
|
||||
pytest.fail("End-of-iteration drift yielded")
|
||||
assert not provider.calls
|
||||
|
||||
|
||||
def test_result_consumption_drift_cannot_yield(settings):
|
||||
provider = FakeProvider(settings)
|
||||
class Results:
|
||||
def __len__(self): return 1
|
||||
def __iter__(self):
|
||||
yield [1, 0, 0]
|
||||
drift(provider, "model")
|
||||
provider.embed = lambda texts: Results()
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")],
|
||||
processing_profile=deepcopy(profile(settings, provider))):
|
||||
pytest.fail("Result-consumption drift yielded")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["text", "section"])
|
||||
@pytest.mark.parametrize("invalid", ["nul\x00value", "bad\ud800", "bad\udfff"])
|
||||
def test_database_incompatible_strings_fail_before_embedding(settings, field, invalid):
|
||||
provider = FakeProvider(settings)
|
||||
chunk = replace(ChunkDraft(0, "a", section="source"), **{field: invalid})
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[chunk],
|
||||
processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Database-incompatible chunk yielded")
|
||||
assert not caught.value.retryable and not provider.calls
|
||||
|
||||
|
||||
def vision_chunks(settings, section):
|
||||
configured = settings.model_copy(update={"vision_provider": "test-vision",
|
||||
"vision_endpoint": "https://vision.invalid/v1", "vision_model": "actual-model"})
|
||||
provider = FakeProvider(configured)
|
||||
frozen = profile(configured, provider)
|
||||
envelope = ExtractionEnvelope(document_id=uuid4(), title="sample", original_sha256="a" * 64,
|
||||
extraction_profile_sha256=extraction_profile_digest(frozen), normalization_policy=frozen["normalizer"],
|
||||
complete=True, quality_decision="passed",
|
||||
blocks=(ExtractedBlock(ordinal=0, block_id="image", text="Reliable complete source evidence.",
|
||||
section=section, source_locator="image/1", method="vision", actual_model="actual-model"),))
|
||||
payload = serialize_artifact(envelope, frozen)
|
||||
restored = validate_artifact(payload, artifact_sha256=hashlib.sha256(payload).hexdigest(),
|
||||
document_id=envelope.document_id, original_sha256=envelope.original_sha256, processing_profile=frozen)
|
||||
return provider, frozen, envelope.document_id, chunk_extraction(restored, frozen)
|
||||
|
||||
|
||||
def test_vision_envelope_chunking_nul_location_reproduction(settings):
|
||||
provider, frozen, document, chunks = vision_chunks(settings, "image\x00section")
|
||||
assert "\x00" in chunks[0].section
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=document, chunks=chunks, processing_profile=frozen):
|
||||
pytest.fail("NUL from vision evidence escaped staging")
|
||||
assert not caught.value.retryable and not provider.calls
|
||||
|
||||
|
||||
def test_persian_zwnj_newlines_remain_faithful(settings):
|
||||
provider = FakeProvider(settings)
|
||||
text, section = "متن معتبر\u200c فارسی\r\nشرایط کامل", "بخش\u200c یک\nصفحه"
|
||||
provider.request_policy["limits"]["max_input_units"] = 200
|
||||
provider.request_policy["limits"]["max_batch_units"] = 400
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, text, section=section)],
|
||||
processing_profile=profile(settings, provider)) as staged:
|
||||
assert staged.chunks[0].text == text and staged.chunks[0].section == section
|
||||
assert provider.calls == [(text.replace("\r\n", "\n"),)]
|
||||
|
||||
|
||||
PERMANENT_CODES = ["insufficient_quota", "credit_balance_exhausted",
|
||||
"organization_spend_limit_exceeded", "project_spend_limit_exceeded",
|
||||
"organization_usage_limit_exceeded"]
|
||||
|
||||
|
||||
def error_http(monkeypatch, body, *, status=429, stream=None, headers=None):
|
||||
stream = BytesIO(body) if stream is None else stream
|
||||
error = HTTPError("https://secret.invalid", status, "private-secret", headers or {}, stream)
|
||||
calls = fake_http(monkeypatch, error=error)
|
||||
return stream, calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["code", "type"])
|
||||
@pytest.mark.parametrize("code", PERMANENT_CODES)
|
||||
def test_quota_credit_spend_errors_are_permanent(settings, monkeypatch, field, code):
|
||||
body = json.dumps({"error": {field: code, "message": "private-secret"}}).encode()
|
||||
stream, calls = error_http(monkeypatch, body)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert not caught.value.retryable
|
||||
assert "private-secret" not in str(caught.value) and len(calls) == 1 and stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", ["rate_limit_exceeded", "slow_down", "unknown_vendor_code"])
|
||||
def test_temporary_or_unknown_429_is_transient(settings, monkeypatch, code):
|
||||
stream, calls = error_http(monkeypatch, json.dumps({"error": {"code": code}}).encode())
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value.retryable and len(calls) == 1 and stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [b"", b"not JSON private-secret", b"null", b"[]",
|
||||
b'{"error":null}', b'{"error":{"code":[]}}', b"[" * 65 + b"0" + b"]" * 65,
|
||||
b"bad\xff", b'{"error":{"code":"insufficient_quota"}}' + b" " * 200])
|
||||
def test_unusable_error_body_falls_back_to_status(settings, monkeypatch, body):
|
||||
stream, calls = error_http(monkeypatch, body)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings, max_response_bytes=100).embed(["a"])
|
||||
assert caught.value.retryable and len(calls) == 1 and stream.closed
|
||||
assert "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
def test_incomplete_quota_json_prefix_does_not_establish_permanent_quota(settings, monkeypatch):
|
||||
body = b'{"error":{"code":"insufficient_quota"}}'
|
||||
native, stream, _ = real_response(monkeypatch, body, declared_length=len(body) + 1)
|
||||
_, calls = error_http(monkeypatch, b"", stream=native)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value.retryable and stream.closed and native.closed and len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("override", [
|
||||
{"profile": None}, {"profile": "private-secret"}, {"profile": {}},
|
||||
{"api_key": None}, {"api_key": 5}, {"api_key": b"private-secret"},
|
||||
{"api_key": "key\x00secret"}, {"api_key": "key\ud800"}, {"api_key": "کلید"},
|
||||
{"api_key": "key\x7f"}, {"api_key": "key with space"},
|
||||
{"limits": None}, {"limits": "private-secret"}, {"limits": {}},
|
||||
{"timeout_seconds": "private-secret"}, {"timeout_seconds": None},
|
||||
{"timeout_seconds": True}, {"timeout_seconds": float("nan")},
|
||||
{"max_response_bytes": False}, {"send_dimensions": 1},
|
||||
])
|
||||
def test_direct_constructor_redacted_permanent(settings, monkeypatch, override):
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings, **override)
|
||||
assert not caught.value.retryable and not calls
|
||||
assert "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field,value", [
|
||||
("endpoint", "https://host:wrong/v1"), ("endpoint", "https://host/v1\x00secret"),
|
||||
("endpoint", "https://host/v1%2fkey"), ("endpoint", "https://host/v1\\key"),
|
||||
("model", "private-secret\ud800"), ("model", "model\x00secret"),
|
||||
("dimensions", True), ("dimensions", 3.5),
|
||||
])
|
||||
def test_direct_profile_values(settings, monkeypatch, field, value):
|
||||
native = deepcopy(settings.embedding_profile)
|
||||
object.__setattr__(native, field, value)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings, profile=native)
|
||||
assert not caught.value.retryable and not calls and "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("counter", [object(), SimpleNamespace(identity="fake:closure"),
|
||||
SimpleNamespace(identity="fake:closure", count=5), SimpleNamespace(identity=[], count=lambda text: 1)])
|
||||
def test_direct_counter_shape(settings, monkeypatch, counter):
|
||||
calls = fake_http(monkeypatch, response())
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200,
|
||||
max_batch_inputs=2, tokenizer="fake:closure")
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings, limits=limits, token_counter=counter)
|
||||
assert not caught.value.retryable and not calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["tokens", "utf8_bytes"])
|
||||
@pytest.mark.parametrize("texts", [None, 4, "a", b"a", [None], [4], [b"a"], ["bad\ud800"], ["bad\udfff"]])
|
||||
def test_direct_embed_preflight(settings, monkeypatch, mode, texts):
|
||||
counter = SimpleNamespace(identity="fake:closure", count=lambda text: 1)
|
||||
limits = dict(unit=mode, max_input_units=100, max_batch_units=200, max_batch_inputs=2,
|
||||
tokenizer=counter.identity if mode == "tokens" else None)
|
||||
provider = adapter(settings, limits=limits, token_counter=counter)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
provider.embed(texts)
|
||||
assert not caught.value.retryable and not calls
|
||||
|
||||
|
||||
def test_unbounded_iterable_not_consumed_by_direct_embed(settings, monkeypatch):
|
||||
provider = adapter(settings)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
consumed = []
|
||||
def inputs():
|
||||
for _ in range(100):
|
||||
consumed.append(1)
|
||||
yield "a"
|
||||
with pytest.raises(EmbeddingError):
|
||||
provider.embed(inputs())
|
||||
assert len(consumed) <= 3 and not calls
|
||||
|
||||
|
||||
def test_duplicate_json_response_fields_are_invalid(settings, monkeypatch):
|
||||
fake_http(monkeypatch, b'{"model":"deterministic-test","data":[{"index":9,"index":0,"embedding":[1,0,0]}]}')
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert not caught.value.retryable
|
||||
|
||||
|
||||
def test_programming_failure_in_counter_is_not_hidden(settings, monkeypatch):
|
||||
def buggy(text): raise RuntimeError("programming defect")
|
||||
counter = SimpleNamespace(identity="fake:closure", count=buggy)
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200,
|
||||
max_batch_inputs=2, tokenizer=counter.identity)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(RuntimeError, match="programming defect"):
|
||||
adapter(settings, limits=limits, token_counter=counter).embed(["a"])
|
||||
assert not calls
|
||||
|
||||
|
||||
def test_programming_failure_in_transport_is_not_hidden(settings, monkeypatch):
|
||||
error = RuntimeError("programming defect")
|
||||
fake_http(monkeypatch, error=error)
|
||||
with pytest.raises(RuntimeError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value is error
|
||||
|
||||
|
||||
def test_classified_counter_error_is_preserved(settings):
|
||||
error = EmbeddingProviderError("classified", retryable=False)
|
||||
def fail(text): raise error
|
||||
counter = SimpleNamespace(identity="fake:closure", count=fail)
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200,
|
||||
max_batch_inputs=2, tokenizer=counter.identity)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings, limits=limits, token_counter=counter).embed(["a"])
|
||||
assert caught.value is error
|
||||
|
||||
@pytest.mark.parametrize("actual", [0, 2])
|
||||
def test_response_iterator_cardinality_must_match_ordinals(settings, actual):
|
||||
provider = FakeProvider(settings)
|
||||
class DishonestLength:
|
||||
def __len__(self): return 1
|
||||
def __iter__(self):
|
||||
for _ in range(actual):
|
||||
yield [1, 0, 0]
|
||||
provider.embed = lambda texts: DishonestLength()
|
||||
with pytest.raises(EmbeddingError):
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")],
|
||||
processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Response iterator cardinality mismatch yielded")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["read", "close"])
|
||||
def test_error_body_deadline_cleanup_capacity_and_late_rejection(settings, monkeypatch, operation):
|
||||
from threading import Event, enumerate as threads
|
||||
entered, release = Event(), Event()
|
||||
class SlowError(BytesIO):
|
||||
def read(self, size):
|
||||
if operation == "read":
|
||||
entered.set()
|
||||
release.wait(3)
|
||||
return super().read(size)
|
||||
def close(self):
|
||||
if operation == "close":
|
||||
entered.set()
|
||||
release.wait(3)
|
||||
super().close()
|
||||
stream = SlowError(b'{"error":{"code":"insufficient_quota"}}')
|
||||
_, calls = error_http(monkeypatch, b"", stream=stream)
|
||||
try:
|
||||
with pytest.raises(EmbeddingProviderError, match="deadline") as caught:
|
||||
adapter(settings, timeout_seconds=.3).embed(["a"])
|
||||
assert caught.value.retryable and entered.is_set()
|
||||
with pytest.raises(EmbeddingProviderError, match="capacity"):
|
||||
adapter(settings).embed(["a"])
|
||||
assert len(calls) == 1
|
||||
finally:
|
||||
release.set()
|
||||
for thread in threads():
|
||||
if thread.name == "embedding-request":
|
||||
thread.join(2)
|
||||
assert stream.closed
|
||||
fake_http(monkeypatch, response())
|
||||
assert len(adapter(settings).embed(["a", "b"])) == 2
|
||||
|
||||
|
||||
def test_error_body_reads_have_a_fixed_upper_bound(settings, monkeypatch):
|
||||
class Recording(BytesIO):
|
||||
consumed = 0
|
||||
def read(self, size):
|
||||
part = super().read(size)
|
||||
self.consumed += len(part)
|
||||
return part
|
||||
stream = Recording(b'{"error":{"code":"insufficient_quota"}}' + b" " * 70000)
|
||||
error_http(monkeypatch, b"", stream=stream)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings, max_response_bytes=128 * 1024).embed(["a"])
|
||||
assert caught.value.retryable and stream.closed and stream.consumed == 64 * 1024 + 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,retryable", [(400, False), (403, False), (408, True), (429, True), (500, True)])
|
||||
def test_empty_native_error_stream_status_fallback(settings, monkeypatch, status, retryable):
|
||||
error = HTTPError("https://private-secret.invalid", status, "private-secret", {}, None)
|
||||
calls = fake_http(monkeypatch, error=error)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value.retryable == retryable and len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["http", "network"])
|
||||
def test_normalized_transport_errors_do_not_retain_raw_context(settings, monkeypatch, kind):
|
||||
from urllib.error import URLError
|
||||
if kind == "http":
|
||||
error_http(monkeypatch, b'{"error":{"code":"insufficient_quota","message":"private-secret"}}')
|
||||
else:
|
||||
fake_http(monkeypatch, error=URLError("private-secret"))
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert caught.value.__context__ is None
|
||||
assert "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
def test_error_stream_cleanup_oserror_is_redacted(settings, monkeypatch):
|
||||
class BadClose(BytesIO):
|
||||
def close(self):
|
||||
super().close()
|
||||
raise OSError("private-secret")
|
||||
stream = BadClose(b'{"error":{"code":"insufficient_quota"}}')
|
||||
error_http(monkeypatch, b"", stream=stream)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert stream.closed and not caught.value.retryable
|
||||
assert "private-secret" not in str(caught.value) and caught.value.__context__ is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_count", [None, True, -1, 0, 1.5, "1"])
|
||||
def test_invalid_actual_token_counts_fail_preflight(settings, monkeypatch, bad_count):
|
||||
counter = SimpleNamespace(identity="fake:closure", count=lambda text: bad_count)
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2,
|
||||
tokenizer=counter.identity)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, limits=limits, token_counter=counter).embed(["a"])
|
||||
assert not calls
|
||||
|
||||
|
||||
def test_surrogate_input_is_rejected_before_tokenizer(settings, monkeypatch):
|
||||
counted = []
|
||||
def count(text):
|
||||
counted.append(text)
|
||||
return 1
|
||||
counter = SimpleNamespace(identity="fake:closure", count=count)
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2,
|
||||
tokenizer=counter.identity)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, limits=limits, token_counter=counter).embed(["bad\ud800"])
|
||||
assert not counted and not calls
|
||||
|
||||
|
||||
def test_latin1_and_unicode_header_keys_are_local_permanent_failures(settings, monkeypatch):
|
||||
calls = fake_http(monkeypatch, response())
|
||||
for key in ("cl\u00e9", "کلید", "key\r\nsecret"):
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, api_key=key)
|
||||
assert not calls
|
||||
|
||||
def test_counter_identity_drift_during_count_is_preflight(settings, monkeypatch):
|
||||
class ChangingCounter:
|
||||
identity = "fake:closure"
|
||||
def count(self, text):
|
||||
self.identity = "different-tokenizer"
|
||||
return 1
|
||||
counter = ChangingCounter()
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2,
|
||||
tokenizer=counter.identity)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, limits=limits, token_counter=counter).embed(["a"])
|
||||
assert not calls
|
||||
|
||||
|
||||
def test_unbounded_sequence_iteration_is_bounded(settings, monkeypatch):
|
||||
from collections.abc import Sequence
|
||||
visited = []
|
||||
class DishonestSequence(Sequence):
|
||||
def __len__(self): return 1
|
||||
def __getitem__(self, index):
|
||||
if index == 100:
|
||||
raise IndexError()
|
||||
visited.append(index)
|
||||
return "a"
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings).embed(DishonestSequence())
|
||||
assert len(visited) <= 3 and not calls
|
||||
|
||||
|
||||
def test_actual_token_count_must_fit_persisted_integer(settings):
|
||||
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 yielded")
|
||||
assert not provider.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity", ["nul\x00identity", "bad\ud800"])
|
||||
def test_tokenizer_identity_is_valid_utf8_database_metadata(settings, monkeypatch, identity):
|
||||
counter = SimpleNamespace(identity=identity, count=lambda text: 1)
|
||||
limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2,
|
||||
tokenizer=identity)
|
||||
calls = fake_http(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, limits=limits, token_counter=counter)
|
||||
assert not calls
|
||||
@@ -0,0 +1,264 @@
|
||||
"""Phase 4 repair regressions; real HTTPResponse framing, no live network."""
|
||||
from array import array
|
||||
from copy import deepcopy
|
||||
from dataclasses import replace
|
||||
from http.client import HTTPResponse
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.documents.embeddings import EmbeddingError, EmbeddingProviderError, packed_vector, stage_document
|
||||
from app.modules.documents.types import ChunkDraft
|
||||
from tests.unit.test_phase4 import FakeProvider, adapter, fake_http, profile, response
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vector", [[1e-30, 0, 0], [1e20, 0, 0], [1e19] * 4])
|
||||
def test_float32_cosine_norm_rejects_unsafe_vectors(vector):
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
packed_vector(vector, len(vector))
|
||||
assert caught.value.retryable is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vector", [[1, 0, 0], [1e-18, 0, 0], [1e18, 0, 0], [1e-30, 1, 0], [1e19] * 3])
|
||||
def test_accepted_vectors_remain_unscaled(vector):
|
||||
assert packed_vector(vector, len(vector)) == array("f", vector).tobytes()
|
||||
|
||||
|
||||
class SocketBytes:
|
||||
def __init__(self, wire):
|
||||
self.stream = BytesIO(wire)
|
||||
def makefile(self, *args):
|
||||
return self.stream
|
||||
|
||||
|
||||
def real_response(monkeypatch, body, *, declared_length=None, chunked=False):
|
||||
headers = (b"Transfer-Encoding: chunked\r\n" if chunked else
|
||||
b"Content-Length: " + str(len(body) if declared_length is None else declared_length).encode() + b"\r\n")
|
||||
socket = SocketBytes(b"HTTP/1.1 200 OK\r\n" + headers + b"\r\n" + body)
|
||||
native = HTTPResponse(socket)
|
||||
native.begin()
|
||||
calls = []
|
||||
class Opener:
|
||||
def open(self, request, timeout):
|
||||
calls.append(request)
|
||||
return native
|
||||
monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener())
|
||||
return native, socket.stream, calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("complete_prefix", [False, True])
|
||||
def test_content_length_premature_eof_is_transient(settings, monkeypatch, complete_prefix):
|
||||
valid = response()
|
||||
body = valid if complete_prefix else valid[:-8]
|
||||
native, stream, calls = real_response(monkeypatch, body, declared_length=len(valid) + 50)
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a", "b"])
|
||||
assert caught.value.retryable
|
||||
assert stream.closed and native.closed and len(calls) == 1
|
||||
# The slot must be available after stream cleanup, without waiting/retrying.
|
||||
fake_http(monkeypatch, valid)
|
||||
assert len(adapter(settings).embed(["a", "b"])) == 2
|
||||
|
||||
|
||||
def test_exact_content_length_is_success(settings, monkeypatch):
|
||||
native, stream, calls = real_response(monkeypatch, response())
|
||||
assert adapter(settings).embed(["a", "b"]) == ((1, 0, 0), (0, 1, 0))
|
||||
assert stream.closed and native.closed and len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("complete", [False, True])
|
||||
def test_chunked_framing_cleanup(settings, monkeypatch, complete):
|
||||
payload = response()
|
||||
body = format(len(payload), "x").encode() + b"\r\n" + payload + b"\r\n"
|
||||
if complete:
|
||||
body += b"0\r\n\r\n"
|
||||
native, stream, calls = real_response(monkeypatch, body, chunked=True)
|
||||
if complete:
|
||||
assert len(adapter(settings).embed(["a", "b"])) == 2
|
||||
else:
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
adapter(settings).embed(["a", "b"])
|
||||
assert caught.value.retryable
|
||||
assert stream.closed and native.closed and len(calls) == 1
|
||||
|
||||
|
||||
def test_framed_response_byte_limit_preserved(settings, monkeypatch):
|
||||
native, stream, _ = real_response(monkeypatch, response())
|
||||
with pytest.raises(EmbeddingError, match="byte limit"):
|
||||
adapter(settings, max_response_bytes=10).embed(["a", "b"])
|
||||
assert stream.closed and native.closed
|
||||
|
||||
|
||||
def test_deep_json_is_redacted_permanent(settings, monkeypatch):
|
||||
nesting = max(2000, sys.getrecursionlimit() + 100)
|
||||
fake_http(monkeypatch, b"[" * nesting + b'"private-secret"' + b"]" * nesting)
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings).embed(["a"])
|
||||
assert not caught.value.retryable and "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
def test_decoder_recursion_is_redacted_permanent(settings, monkeypatch):
|
||||
provider = adapter(settings)
|
||||
monkeypatch.setattr(provider, "_request_once", lambda request: b"{}")
|
||||
def recursive(*args, **kwargs):
|
||||
raise RecursionError("private-secret")
|
||||
monkeypatch.setattr("app.infrastructure.openai_embeddings.json.loads", recursive)
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
provider.embed(["a"])
|
||||
assert not caught.value.retryable and "private-secret" not in str(caught.value)
|
||||
|
||||
|
||||
def test_excessive_nesting_in_unused_field_is_rejected(settings, monkeypatch):
|
||||
# Valid shallow result must not permit pathological nesting elsewhere.
|
||||
body = response()[:-1] + b',"unused":' + b"[" * 65 + b"0" + b"]" * 65 + b"}"
|
||||
fake_http(monkeypatch, body)
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
adapter(settings).embed(["a", "b"])
|
||||
assert not caught.value.retryable
|
||||
|
||||
|
||||
def test_json_string_braces_and_escapes_do_not_count_as_nesting(settings, monkeypatch):
|
||||
value = json.loads(response())
|
||||
value["unused"] = '{"' * 100 + '\\' + '"'
|
||||
fake_http(monkeypatch, json.dumps(value).encode())
|
||||
assert len(adapter(settings).embed(["a", "b"])) == 2
|
||||
|
||||
|
||||
PROFILE_CASES = [
|
||||
("root", None), ("root", []), ("root", "private-secret"),
|
||||
("limits", None), ("limits", []), ("limits", {}),
|
||||
("limits.max_staged_bytes", None), ("limits.max_staged_bytes", "private-secret"),
|
||||
("limits.max_staged_bytes", True), ("limits.max_staged_bytes", 0),
|
||||
("limits.max_staged_bytes", 1.5),
|
||||
("limits.embedding_batch_size", None), ("limits.embedding_batch_size", "private-secret"),
|
||||
("limits.embedding_batch_size", 100.5), ("limits.embedding_batch_size", 0),
|
||||
("limits.embedding_batch_size", True),
|
||||
("limits.max_chunks", None), ("limits.max_chunks", "private-secret"),
|
||||
("limits.max_chunks", False), ("limits.max_chunks", -1), ("limits.max_chunks", 1.5),
|
||||
("normalizer", None), ("normalizer", []), ("normalizer", "private-secret"),
|
||||
("missing", "limits"), ("missing", "normalizer"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,value", PROFILE_CASES)
|
||||
def test_malformed_profiles_are_permanent_and_no_provider_call(settings, path, value):
|
||||
provider = FakeProvider(settings)
|
||||
frozen = deepcopy(profile(settings, provider))
|
||||
if path == "root":
|
||||
frozen = value
|
||||
elif path == "missing":
|
||||
frozen.pop(value)
|
||||
elif "." in path:
|
||||
parent, child = path.split(".")
|
||||
frozen[parent][child] = value
|
||||
else:
|
||||
frozen[path] = value
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen):
|
||||
pytest.fail("Malformed profile yielded")
|
||||
assert not caught.value.retryable and "private-secret" not in str(caught.value)
|
||||
assert not provider.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["max_staged_bytes", "embedding_batch_size", "max_chunks"])
|
||||
def test_missing_staging_limit_is_permanent(settings, field):
|
||||
provider = FakeProvider(settings)
|
||||
frozen = profile(settings, provider)
|
||||
frozen["limits"].pop(field)
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen):
|
||||
pytest.fail("Missing limit yielded")
|
||||
assert not caught.value.retryable and not provider.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunks", [
|
||||
None, 5, [None], [object()], [{"ordinal": 0, "text": "private-secret"}], ["private-secret"],
|
||||
[ChunkDraft(0, None)], [ChunkDraft(0, 10)], [ChunkDraft(0, ["private-secret"])],
|
||||
[ChunkDraft(0, b"private-secret")], [ChunkDraft(0, "private-secret\ud800")],
|
||||
])
|
||||
def test_malformed_drafts_are_redacted_permanent(settings, chunks):
|
||||
provider = FakeProvider(settings)
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Malformed draft yielded")
|
||||
assert not caught.value.retryable and "private-secret" not in str(caught.value)
|
||||
assert not provider.calls
|
||||
|
||||
|
||||
def test_invalid_profile_json_is_redacted(settings):
|
||||
provider = FakeProvider(settings)
|
||||
frozen = profile(settings, provider)
|
||||
frozen["unexpected"] = float("nan")
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen):
|
||||
pytest.fail("Invalid profile serialization yielded")
|
||||
assert not caught.value.retryable
|
||||
|
||||
|
||||
def test_classified_provider_error_is_preserved(settings):
|
||||
provider = FakeProvider(settings)
|
||||
error = EmbeddingProviderError("safe transient", retryable=True)
|
||||
def fail(texts):
|
||||
raise error
|
||||
provider.embed = fail
|
||||
with pytest.raises(EmbeddingProviderError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Failed provider yielded")
|
||||
assert caught.value is error and caught.value.retryable
|
||||
|
||||
|
||||
def test_consumer_validation_exception_is_not_reclassified_and_releases(settings):
|
||||
provider = FakeProvider(settings)
|
||||
error = KeyError("consumer fault")
|
||||
with pytest.raises(KeyError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=profile(settings, provider)) as staged:
|
||||
raise error
|
||||
assert caught.value is error and staged.closed
|
||||
|
||||
def test_premature_eof_cleanup_retains_capacity_until_exit(settings, monkeypatch):
|
||||
from threading import Event, enumerate as threads
|
||||
entered, release = Event(), Event()
|
||||
native, stream, _ = real_response(monkeypatch, response(), declared_length=len(response()) + 1)
|
||||
close = native.close
|
||||
def blocked_close():
|
||||
entered.set()
|
||||
release.wait(3)
|
||||
close()
|
||||
native.close = blocked_close
|
||||
try:
|
||||
with pytest.raises(EmbeddingProviderError, match="deadline"):
|
||||
adapter(settings, timeout_seconds=.3).embed(["a", "b"])
|
||||
assert entered.is_set()
|
||||
with pytest.raises(EmbeddingProviderError, match="capacity"):
|
||||
adapter(settings).embed(["a", "b"])
|
||||
finally:
|
||||
release.set()
|
||||
for thread in threads():
|
||||
if thread.name == "embedding-request":
|
||||
thread.join(2)
|
||||
assert native.closed and stream.closed
|
||||
fake_http(monkeypatch, response())
|
||||
assert len(adapter(settings).embed(["a", "b"])) == 2
|
||||
|
||||
|
||||
def test_depth_limit_boundary(settings, monkeypatch):
|
||||
# Root object contributes one level: 63 arrays give total depth 64.
|
||||
body = response()[:-1] + b',"unused":' + b"[" * 63 + b"0" + b"]" * 63 + b"}"
|
||||
fake_http(monkeypatch, body)
|
||||
assert len(adapter(settings).embed(["a", "b"])) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("broken", [None, {}, {"unit": "private-secret"}])
|
||||
def test_invalid_frozen_request_limits_are_redacted(settings, broken):
|
||||
provider = FakeProvider(settings)
|
||||
provider.request_policy["limits"] = broken
|
||||
with pytest.raises(EmbeddingError) as caught:
|
||||
with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")],
|
||||
processing_profile=profile(settings, provider)):
|
||||
pytest.fail("Malformed request limits yielded")
|
||||
assert not caught.value.retryable and "private-secret" not in str(caught.value)
|
||||
assert not provider.calls
|
||||
@@ -0,0 +1,354 @@
|
||||
"""Phase 4 repairs for vector validation, float32 cosine safety, timeout limits, and endpoint hostnames."""
|
||||
from array import array
|
||||
from copy import deepcopy
|
||||
from dataclasses import replace
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
import threading
|
||||
from threading import Event, Thread
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import ValidationError
|
||||
import pytest
|
||||
|
||||
from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings, _CAPACITY
|
||||
from app.modules.documents.embeddings import (
|
||||
EmbeddingError, EmbeddingProviderError, packed_vector, stage_document,
|
||||
is_representable_timeout, validate_endpoint_hostname,
|
||||
)
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
from app.modules.documents.types import ChunkDraft
|
||||
from tests.unit.test_phase4 import FakeProvider, adapter, fake_http, profile, response
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Finding 1: Vector validation and packing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class DishonestSequence:
|
||||
def __init__(self, reported_len, items):
|
||||
self.reported_len = reported_len
|
||||
self.items = items
|
||||
|
||||
def __len__(self):
|
||||
return self.reported_len
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.items)
|
||||
|
||||
|
||||
class EndlessSequence:
|
||||
def __init__(self, reported_len):
|
||||
self.reported_len = reported_len
|
||||
self.consumed = 0
|
||||
|
||||
def __len__(self):
|
||||
return self.reported_len
|
||||
|
||||
def __iter__(self):
|
||||
while True:
|
||||
self.consumed += 1
|
||||
yield 1.0
|
||||
|
||||
|
||||
class ChangingSequence:
|
||||
def __init__(self, first_items, second_items):
|
||||
self.first_items = first_items
|
||||
self.second_items = second_items
|
||||
self.traversals = 0
|
||||
|
||||
def __len__(self):
|
||||
return len(self.first_items)
|
||||
|
||||
def __iter__(self):
|
||||
self.traversals += 1
|
||||
if self.traversals == 1:
|
||||
return iter(self.first_items)
|
||||
return iter(self.second_items)
|
||||
|
||||
|
||||
def test_packed_vector_rejects_dishonest_longer_sequence():
|
||||
dishonest = DishonestSequence(3, [1.0, 0.0, 0.0, 0.0])
|
||||
with pytest.raises(EmbeddingError, match="dimension mismatch"):
|
||||
packed_vector(dishonest, 3)
|
||||
|
||||
|
||||
def test_packed_vector_rejects_dishonest_shorter_sequence():
|
||||
dishonest = DishonestSequence(3, [1.0, 0.0])
|
||||
with pytest.raises(EmbeddingError, match="dimension mismatch"):
|
||||
packed_vector(dishonest, 3)
|
||||
|
||||
|
||||
def test_packed_vector_bounded_stopping_on_endless_sequence():
|
||||
endless = EndlessSequence(3)
|
||||
with pytest.raises(EmbeddingError, match="dimension mismatch"):
|
||||
packed_vector(endless, 3)
|
||||
# Must stop after consuming at most D + 1 (3 + 1 = 4) elements
|
||||
assert endless.consumed == 4
|
||||
|
||||
|
||||
def test_packed_vector_validates_and_packs_captured_elements_once():
|
||||
# If traversed a second time, it would yield NaN which fails validation.
|
||||
# Because packed_vector traverses only once and packs the captured elements, it succeeds.
|
||||
changing = ChangingSequence([1.0, 0.0, 0.0], [float("nan"), 0.0, 0.0])
|
||||
result = packed_vector(changing, 3)
|
||||
assert result == array("f", [1.0, 0.0, 0.0]).tobytes()
|
||||
assert changing.traversals == 1
|
||||
|
||||
|
||||
def test_packed_vector_accepts_single_use_iterator():
|
||||
iterator = iter([1.0, 0.0, 0.0])
|
||||
result = packed_vector(iterator, 3)
|
||||
assert result == array("f", [1.0, 0.0, 0.0]).tobytes()
|
||||
|
||||
|
||||
def test_packed_vector_exact_byte_storage():
|
||||
for d in (1, 3, 16, 128):
|
||||
vec = [1.0] + [0.0] * (d - 1)
|
||||
packed = packed_vector(vec, d)
|
||||
assert len(packed) == 4 * d
|
||||
|
||||
|
||||
def test_stage_document_cleans_up_on_failed_final_batch(settings):
|
||||
# Setup document with two batches of chunks
|
||||
doc_id = uuid4()
|
||||
chunks = [
|
||||
ChunkDraft(0, "text 0", token_count=1),
|
||||
ChunkDraft(1, "text 1", token_count=1),
|
||||
]
|
||||
|
||||
class FailingSecondBatchProvider:
|
||||
def __init__(self, base_profile):
|
||||
self.profile = base_profile
|
||||
self.request_policy = dict(
|
||||
limits=dict(unit="tokens", tokenizer="tiktoken:cl100k_base",
|
||||
max_input_units=100, max_batch_units=200, max_batch_inputs=1),
|
||||
timeout_seconds=60.0, send_dimensions=False, max_response_bytes=1048576,
|
||||
)
|
||||
self.batch_count = 0
|
||||
|
||||
def embed(self, texts):
|
||||
self.batch_count += 1
|
||||
if self.batch_count == 1:
|
||||
return [[1.0, 0.0, 0.0]]
|
||||
# Second batch returns mismatched vector
|
||||
return [[1.0, 0.0]]
|
||||
|
||||
prov = FailingSecondBatchProvider(settings.embedding_profile)
|
||||
prof = profile(settings, prov, embedding_batch_size=1)
|
||||
prof["embedding_request"] = prov.request_policy
|
||||
|
||||
class Counter:
|
||||
identity = "tiktoken:cl100k_base"
|
||||
def count(self, text):
|
||||
return 1
|
||||
|
||||
with pytest.raises(EmbeddingError, match="dimension mismatch"):
|
||||
with stage_document(prov, document_id=doc_id, chunks=chunks,
|
||||
processing_profile=prof, token_counter=Counter()):
|
||||
pass
|
||||
|
||||
|
||||
def test_stage_document_dishonest_vector_does_not_bypass_staging_budget(settings):
|
||||
doc_id = uuid4()
|
||||
chunks = [ChunkDraft(0, "text 0", token_count=1)]
|
||||
|
||||
class DishonestProvider:
|
||||
def __init__(self, base_profile):
|
||||
self.profile = base_profile
|
||||
self.request_policy = dict(
|
||||
limits=dict(unit="tokens", tokenizer="tiktoken:cl100k_base",
|
||||
max_input_units=100, max_batch_units=200, max_batch_inputs=1),
|
||||
timeout_seconds=60.0, send_dimensions=False, max_response_bytes=1048576,
|
||||
)
|
||||
|
||||
def embed(self, texts):
|
||||
return [DishonestSequence(3, [1.0] * 1000)]
|
||||
|
||||
prov = DishonestProvider(settings.embedding_profile)
|
||||
prof = profile(settings, prov, max_staged_bytes=100_000)
|
||||
prof["embedding_request"] = prov.request_policy
|
||||
|
||||
class Counter:
|
||||
identity = "tiktoken:cl100k_base"
|
||||
def count(self, text):
|
||||
return 1
|
||||
|
||||
with pytest.raises(EmbeddingError, match="dimension mismatch"):
|
||||
with stage_document(prov, document_id=doc_id, chunks=chunks,
|
||||
processing_profile=prof, token_counter=Counter()):
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Finding 2: Float32 cosine safety without rescaling
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("vector", [
|
||||
[3e-23, 0, 0],
|
||||
[1e-21] * 16000,
|
||||
[1e-21] * 3,
|
||||
[1e-30, 0, 0],
|
||||
[1e20, 0, 0],
|
||||
[1e19] * 4,
|
||||
])
|
||||
def test_float32_cosine_safety_rejects_unsafe_vectors(vector):
|
||||
with pytest.raises(EmbeddingError) as exc:
|
||||
packed_vector(vector, len(vector))
|
||||
assert exc.value.retryable is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vector", [
|
||||
[1, 0, 0],
|
||||
[1e-18, 0, 0],
|
||||
[1e18, 0, 0],
|
||||
[1e-30, 1, 0],
|
||||
[1e19] * 3,
|
||||
])
|
||||
def test_float32_cosine_safety_preserves_safe_vectors_unscaled(vector):
|
||||
assert packed_vector(vector, len(vector)) == array("f", vector).tobytes()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Finding 3: Reject runtime-unrepresentable embedding timeouts
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_timeout_1e20_rejected_before_mock_transport_without_starting_thread(settings, monkeypatch):
|
||||
entered = Event()
|
||||
class Opener:
|
||||
def open(self, request, timeout):
|
||||
entered.set()
|
||||
return BytesIO(b"{}")
|
||||
monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener())
|
||||
|
||||
initial_threads = threading.active_count()
|
||||
# Capacity must not be held
|
||||
assert _CAPACITY.acquire(blocking=False)
|
||||
_CAPACITY.release()
|
||||
|
||||
with pytest.raises(EmbeddingError) as exc:
|
||||
adapter(settings, timeout_seconds=1e20)
|
||||
assert exc.value.retryable is False
|
||||
assert "private-secret" not in str(exc.value)
|
||||
|
||||
# Verify no mock transport was entered and no thread started
|
||||
assert not entered.is_set()
|
||||
assert threading.active_count() == initial_threads
|
||||
# Transport capacity must still be free
|
||||
assert _CAPACITY.acquire(blocking=False)
|
||||
_CAPACITY.release()
|
||||
|
||||
|
||||
def test_timeout_1e20_rejected_from_settings(settings):
|
||||
values = settings.model_dump()
|
||||
values["embedding_timeout_seconds"] = 1e20
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
IngestionSettings(_env_file=None, **values)
|
||||
assert "private-secret" not in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_timeout", [
|
||||
1e20, 1e10, 2147484.0, 0, -1, float("inf"), float("nan"), "60", True, None,
|
||||
])
|
||||
def test_timeout_boundaries_rejected(settings, invalid_timeout):
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, timeout_seconds=invalid_timeout)
|
||||
|
||||
|
||||
def test_timeout_representable_boundary_accepted(settings):
|
||||
# 2147483.0 is the valid boundary for 32-bit timeval
|
||||
adv = adapter(settings, timeout_seconds=2147483.0)
|
||||
assert adv.timeout == 2147483.0
|
||||
assert adv.request_policy["timeout_seconds"] == 2147483.0
|
||||
|
||||
|
||||
def test_ordinary_deadline_expires_and_cleans_up_capacity(settings, monkeypatch):
|
||||
release = Event()
|
||||
entered = Event()
|
||||
calls = []
|
||||
|
||||
class Opener:
|
||||
def open(self, request, timeout):
|
||||
calls.append(1)
|
||||
entered.set()
|
||||
release.wait(2)
|
||||
return BytesIO(response())
|
||||
|
||||
monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener())
|
||||
adv = adapter(settings, timeout_seconds=0.1)
|
||||
|
||||
try:
|
||||
with pytest.raises(EmbeddingProviderError) as exc:
|
||||
adv.embed(["test"])
|
||||
assert exc.value.retryable is True
|
||||
assert entered.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
# Once released, capacity is freed and next call succeeds
|
||||
deadline = time.monotonic() + 1.0
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
adv2 = adapter(settings, timeout_seconds=1.0)
|
||||
break
|
||||
except EmbeddingProviderError:
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Finding 4: Reject locally invalid endpoint hostnames
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("invalid_endpoint", [
|
||||
"https://example..com/v1",
|
||||
"https://.example.com/v1",
|
||||
"https://example.com./v1",
|
||||
"https://" + "a" * 64 + ".com/v1",
|
||||
"https://-example.com/v1",
|
||||
"https://example-.com/v1",
|
||||
"https://999.999.999.999/v1",
|
||||
"https://::1/v1",
|
||||
"https://[invalid::ipv6]/v1",
|
||||
])
|
||||
def test_endpoint_hostname_rejected_direct_and_settings(settings, invalid_endpoint):
|
||||
prof = replace(settings.embedding_profile, endpoint=invalid_endpoint)
|
||||
with pytest.raises(EmbeddingError):
|
||||
adapter(settings, profile=prof)
|
||||
|
||||
values = settings.model_dump()
|
||||
values["embedding_endpoint"] = invalid_endpoint
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
IngestionSettings(_env_file=None, **values)
|
||||
assert "dummy-url-secret" not in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("valid_endpoint", [
|
||||
"https://api.openai.com/v1",
|
||||
"https://" + "a" * 63 + ".com/v1",
|
||||
"https://localhost:8080/v1",
|
||||
"https://127.0.0.1:8000/v1",
|
||||
"https://[::1]:8000/v1",
|
||||
"https://[2001:db8::1]/v1",
|
||||
"https://Example.invalid:8443/tenant/deployment-01/v1/",
|
||||
])
|
||||
def test_endpoint_hostname_preserves_valid_endpoints(settings, valid_endpoint):
|
||||
prof = replace(settings.embedding_profile, endpoint=valid_endpoint)
|
||||
adv = adapter(settings, profile=prof)
|
||||
assert adv.profile.endpoint == valid_endpoint
|
||||
|
||||
|
||||
def test_programming_failures_propagate_without_blanket_handler(settings, monkeypatch):
|
||||
from collections.abc import Mapping
|
||||
class BuggyLimits(Mapping):
|
||||
def __getitem__(self, key):
|
||||
raise ZeroDivisionError("Simulated programming bug")
|
||||
def __iter__(self):
|
||||
raise ZeroDivisionError("Simulated programming bug")
|
||||
def __len__(self):
|
||||
return 1
|
||||
|
||||
prof = settings.embedding_profile
|
||||
with pytest.raises(ZeroDivisionError):
|
||||
OpenAICompatibleEmbeddings(profile=prof, api_key="secret", limits=BuggyLimits())
|
||||
Reference in New Issue
Block a user