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