Files
amirhosein mazaheri 39ed0422c5 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
2026-10-07 16:21:17 +03:30

472 lines
22 KiB
Python

"""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