- 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
359 lines
16 KiB
Python
359 lines
16 KiB
Python
"""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())
|