- 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
355 lines
12 KiB
Python
355 lines
12 KiB
Python
"""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())
|