Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix(search): decode wrb.fr chunks by JSON grammar, and surface Google's error envelopes (#224)

[email protected]b37dc1d8eb91
diff --git a/fli/search/_wire.py b/fli/search/_wire.py
index 2cbedaa..ef17678 100644
--- a/fli/search/_wire.py
+++ b/fli/search/_wire.py
@@ -3,20 +3,29 @@ r"""Parsing helpers for Google Flights' FlightsFrontendService wire format.
The Service returns JSONP-flavoured responses of the form::
)]}'\n\n
- <chunk1_byte_len>\n
+ <chunk1_len>\n
[["wrb.fr", null, "<inner JSON string>"]]
- <chunk2_byte_len>\n
+ <chunk2_len>\n
[["wrb.fr", null, "<inner JSON string>"]]
...
`GetShoppingResults` and `GetCalendarGraph` happen to emit a single chunk so
the legacy parsers in this package could get away with `lstrip(")]}'")`.
`GetBookingResults` emits two chunks, so we need a proper multi-chunk reader.
+Since the flight/date searches moved to the public page transport
+(:mod:`fli.search._tfs`), `SearchFlights.get_booking_options` is the only
+live consumer of this module.
-Important quirk: the length headers count UTF-8 **bytes**, not Python string
-characters. When the response contains any non-ASCII characters (which it
-sometimes does — airport names, airline names) the offsets diverge, so the
-reader must operate over the byte representation of the body.
+Important quirk: the length headers are **not** a dependable frame
+delimiter. They count the chunk plus its two surrounding newlines, but in
+characters rather than UTF-8 bytes, so any response carrying non-ASCII text
+(accented airport or airline names) desynchronises a byte-oriented reader —
+and an ASCII response hides the difference entirely. Rather than encode a
+guess about Google's convention, this reader ignores the announced length
+and lets the JSON grammar delimit each chunk, which is correct either way.
+The headers' *positions* are still used — to re-synchronise after a
+malformed chunk, and to bound each decode to one chunk's worth of text —
+but their values never are.
This module centralises that reader and exposes :func:`iter_wrb_chunks` which
yields the decoded inner JSON of each ``wrb.fr`` chunk.
@@ -26,78 +35,261 @@ from __future__ import annotations
import json
import logging
+import re
from collections.abc import Iterator
-from typing import Any
+from typing import Any, NamedTuple
+
+from fli.search.exceptions import _GRPC_STATUS_NAMES, SearchRejectedError
logger = logging.getLogger(__name__)
-_PREFIX = b")]}'"
+_PREFIX = ")]}'"
+
+# Framing noise between two chunks: the length header and the newlines
+# around it. Skipped wholesale — the header's value is never trusted.
+_FRAMING_CHARS = "0123456789 \t\r\n"
+
+# A chunk boundary in the raw stream: line break, decimal length header,
+# line break, then the "[" that opens the next chunk. CRLF is accepted so
+# a CRLF-framed body gets the same bounded decode as an LF-framed one —
+# but only as the trailing ``\r?``. A CRLF ends in "\n", so anchoring the
+# pattern on a literal "\n" still matches "\r\n<digits>\r\n[" (one
+# character later, which only leaves the "\r" in the window as trailing
+# whitespace the decoder ignores) while keeping the engine's literal-prefix
+# scan. Spelling the first break "\r?\n" instead costs it: a 20 MB body
+# went from 61 ms to 172 ms purely on that.
+#
+# This pattern cannot occur inside a well-formed JSON document, so the
+# next match is always at or after the current chunk's end. CR and LF are
+# both illegal unescaped inside a JSON string, so the digits would have to
+# be a number token surrounded by whitespace — and a number followed by
+# "[" with only whitespace between them is not valid JSON in any container
+# (an array needs a comma, an object a comma or colon, and a top-level
+# document ends after its one value). That makes the match position a safe
+# upper bound for where the current chunk ends, which is what lets the
+# decode below work on a bounded window. Only the header's *position* is
+# used; its value is still never trusted.
+# ``TestChunkBoundaryCannotSplitAValue`` enumerates the claim.
+_CHUNK_BOUNDARY = re.compile(r"\n\d+\r?\n(?=\[)")
+
+# Error details are echoed into the exception message, so cap them.
+_MAX_DETAIL_CHARS = 200
+
+# A body of nothing but bad chunks would otherwise emit one warning per
+# chunk. Warn on the first few, then say how many there were in total.
+_MAX_MALFORMED_WARNINGS = 5
+
+# Row kinds emitted by :func:`_rows_from_outer`.
+_ROW_CHUNK = "chunk"
+_ROW_ERROR = "error"
+
+
+class _RejectionStatus(NamedTuple):
+ """A rejection reported by an error-envelope ``wrb.fr`` row."""
+
+ code: int
+ detail: str | None
def iter_wrb_chunks(body: str | bytes) -> Iterator[Any]:
"""Yield the inner JSON object of every ``wrb.fr`` chunk in ``body``.
Robust to single-chunk responses with no length headers (the older
- ``GetShoppingResults`` / ``GetCalendarGraph`` shape) — those are parsed
- by falling back to a single JSON load over the trimmed body.
- """
- if isinstance(body, str):
- raw = body.encode("utf-8")
- else:
- raw = body
+ ``GetShoppingResults`` / ``GetCalendarGraph`` shape) — those parse the
+ same way, since chunk boundaries are derived from the JSON itself.
- raw = raw.lstrip()
- if raw.startswith(_PREFIX):
- raw = raw[len(_PREFIX) :]
- raw = raw.lstrip()
+ A response may mix payload chunks and an error row, and where the error
+ sits decides what happens:
- if not raw:
- return
+ * an error row reached **before** any usable chunk means the request
+ itself was rejected, so it raises immediately — handing the caller
+ the chunks behind it would pass off a partial answer as a whole one;
+ * an error row **trailing** chunks that already parsed keeps those
+ chunks and logs the rejection, so the outcome does not depend on how
+ far the caller happens to drain the generator.
- # Fast path: no length headers (legacy single-chunk responses).
- if not (b"0" <= raw[:1] <= b"9"):
- try:
- outer = json.loads(raw.decode("utf-8"))
- except (ValueError, json.JSONDecodeError, UnicodeDecodeError) as exc:
- logger.warning("Failed to decode single-chunk wrb.fr body as JSON: %s", exc)
- logger.debug("single-chunk wrb.fr decode failed", exc_info=True)
- return
- yield from _chunks_from_outer(outer)
- return
+ Nothing else escapes: a chunk that cannot be decoded — malformed,
+ truncated or nested past the decoder's recursion limit — is skipped
+ with a warning.
+
+ Raises:
+ SearchRejectedError: If Google answered with an error envelope
+ before any usable chunk. See :func:`_error_status`.
+
+ """
+ # ``errors="replace"`` keeps a corrupted transfer from raising here;
+ # the resulting chunk simply fails to parse and is reported below.
+ text = body.decode("utf-8", errors="replace") if isinstance(body, bytes) else body
+
+ text = text.lstrip()
+ if text.startswith(_PREFIX):
+ text = text[len(_PREFIX) :]
+ text = text.lstrip()
+ decoder = json.JSONDecoder()
+ trailing: list[_RejectionStatus] = []
+ malformed = 0
+ yielded = 0
cursor = 0
- while cursor < len(raw):
- # Read the decimal length prefix terminated by \n.
- end = raw.find(b"\n", cursor)
- if end == -1:
+ size = len(text)
+ # Lookahead and window state, carried across chunks on purpose — see below.
+ boundary: re.Match[str] | None = None
+ no_more_boundaries = False
+ region = text
+ region_start = 0
+ while cursor < size:
+ while cursor < size and text[cursor] in _FRAMING_CHARS:
+ cursor += 1
+ if cursor >= size:
break
+
+ # Decode within the region ending at the next boundary rather than
+ # over the whole body. A failed decode builds a ``JSONDecodeError``,
+ # and that constructor counts the newlines before the error position
+ # — O(offset) over whatever string it was handed. Passing the full
+ # body made a stream of bad chunks quadratic; a bounded region keeps
+ # every failure proportional to the region, and a failure jumps
+ # straight to the region's end, so there is at most one per region.
+ #
+ # Both the lookahead and the slice are computed per REGION, not per
+ # chunk, and that is what keeps this linear:
+ #
+ # * the search is cached because boundaries only move forward. A
+ # match found for an earlier cursor is still the next one until the
+ # cursor passes it (there can be nothing between them, or the
+ # search would have returned that instead), and once a search comes
+ # back empty there is nothing ahead to find again. Without both, a
+ # body with no boundary at all — CRLF framing, or chunks written
+ # back to back with no headers — pays a scan to the end of the
+ # document once per chunk.
+ # * the slice is cached with it, and the cursor is translated into
+ # it, because re-slicing ``text[cursor:boundary.start()]`` per
+ # chunk copies the whole remaining region every time. With one
+ # boundary at the end of an 80k-chunk body that came to ~105 GB of
+ # copying, 1.6 s against 81 ms for the reader that never sliced.
+ #
+ # Both hazards are invisible on the shape Google actually sends,
+ # where every chunk has a boundary right behind it and the region is
+ # one chunk long.
+ if not no_more_boundaries and (boundary is None or boundary.start() < cursor):
+ boundary = _CHUNK_BOUNDARY.search(text, cursor)
+ no_more_boundaries = boundary is None
+ if boundary is None:
+ region, region_start = text, 0
+ else:
+ region, region_start = text[cursor : boundary.start()], cursor
+
try:
- length = int(raw[cursor:end])
- except ValueError:
- logger.warning(
- "Malformed length header at offset %d; truncating chunk stream",
- cursor,
- )
- break
- # Google's length header counts the leading newline after the header
- # AND the trailing newline that separates this chunk from the next.
- # We've already consumed the leading newline (it terminated the header),
- # so we read `length - 1` bytes which gives JSON + trailing \n.
- cursor = end + 1
- chunk_bytes = max(length - 1, 0)
- payload = raw[cursor : cursor + chunk_bytes]
- cursor += chunk_bytes
- try:
- outer = json.loads(payload.strip().decode("utf-8"))
- except (ValueError, json.JSONDecodeError, UnicodeDecodeError) as exc:
- logger.warning("Discarding malformed wrb.fr chunk: %s", exc)
- logger.debug("malformed wrb.fr chunk", exc_info=True)
+ outer, consumed = decoder.raw_decode(region, cursor - region_start)
+ except (ValueError, RecursionError) as exc:
+ # ``RecursionError`` is a ``RuntimeError``: deeply nested input
+ # would otherwise escape the generator entirely.
+ malformed += 1
+ if malformed <= _MAX_MALFORMED_WARNINGS:
+ logger.warning("Discarding malformed wrb.fr chunk: %s", exc)
+ logger.debug("malformed wrb.fr chunk", exc_info=True)
+ if boundary is None:
+ break
+ cursor = boundary.end()
continue
- yield from _chunks_from_outer(outer)
+ cursor = region_start + consumed
+
+ for kind, value in _rows_from_outer(outer):
+ if kind is _ROW_ERROR:
+ if not yielded:
+ raise _rejection(value)
+ trailing.append(value)
+ continue
+ yielded += 1
+ yield value
+
+ if malformed > _MAX_MALFORMED_WARNINGS:
+ logger.warning("Discarded %d malformed wrb.fr chunks in total", malformed)
+ if trailing:
+ status = trailing[0]
+ logger.warning(
+ "Google Flights reported error %d (%s) alongside %d usable chunk(s); "
+ "keeping the partial payload",
+ status.code,
+ status.detail or _GRPC_STATUS_NAMES.get(status.code) or "unknown",
+ yielded,
+ )
-def _chunks_from_outer(outer: Any) -> Iterator[Any]:
- """Walk a top-level chunk list and yield decoded inner-JSON payloads."""
+
+def _rejection(status: _RejectionStatus) -> SearchRejectedError:
+ """Build the exception describing a rejected request."""
+ return SearchRejectedError(status.code, detail=status.detail)
+
+
+def _error_status(row: list[Any]) -> _RejectionStatus | None:
+ """Return the status of an error-envelope ``wrb.fr`` row, if any.
+
+ Google reports a rejected request with ``HTTP 200`` and a payload-less
+ row of the shape ``["wrb.fr", null, null, null, null, [code]]``, e.g.
+ ``3`` (``INVALID_ARGUMENT``) for a payload it cannot decode or ``13``
+ (``INTERNAL``) for a request it declines to serve. The status may carry
+ a message and a ``google.rpc``-style detail block after the code::
+
+ [13, null, [["type.googleapis.com/…ErrorResponse", [[…, "<req-id>"], 0]]]]
+
+ Only a strictly positive integer code counts as a rejection: ``0`` is
+ gRPC's ``OK`` and would otherwise raise a spurious "error 0", and
+ ``bool`` is excluded because it is a subclass of ``int``.
+ """
+ if len(row) < 6:
+ return None
+ status = row[5]
+ if not isinstance(status, list) or not status:
+ return None
+ code = status[0]
+ if isinstance(code, bool) or not isinstance(code, int) or code <= 0:
+ return None
+ return _RejectionStatus(code, _error_detail(status))
+
+
+def _error_detail(status: list[Any]) -> str | None:
+ """Summarise the message and detail block trailing a status code.
+
+ Every part of this is Google-controlled text of unbounded length, and
+ it ends up in the exception message, in a warning record and — via the
+ CLI's error reporter — in a file under ``~/.fli/logs``. Both halves are
+ capped, and so is the join, so nothing downstream has to defend itself.
+ """
+ parts: list[str] = []
+ message = status[1] if len(status) > 1 else None
+ if isinstance(message, str) and message:
+ parts.append(_truncate(message))
+ details = status[2] if len(status) > 2 else None
+ if details:
+ parts.append(_compact(details))
+ return _truncate("; ".join(parts)) or None
+
+
+def _truncate(text: str) -> str:
+ """Cap ``text`` at :data:`_MAX_DETAIL_CHARS`, marking the cut with an ellipsis."""
+ if len(text) > _MAX_DETAIL_CHARS:
+ return text[: _MAX_DETAIL_CHARS - 1] + "…"
+ return text
+
+
+def _compact(value: Any) -> str:
+ """Render a decoded JSON value as a compact, length-capped string."""
+ try:
+ text = json.dumps(value, separators=(",", ":"), ensure_ascii=False)
+ except (TypeError, ValueError): # pragma: no cover - values come from json.loads
+ text = repr(value)
+ return _truncate(text)
+
+
+def _rows_from_outer(outer: Any) -> Iterator[tuple[str, Any]]:
+ """Yield a top-level chunk list's rows in order, tagged by kind.
+
+ Emits ``(_ROW_CHUNK, payload)`` for a decoded inner payload and
+ ``(_ROW_ERROR, status)`` for an error envelope. The caller needs the
+ original order to tell a rejection from a trailing error, so the two
+ cannot be collected separately.
+ """
if not isinstance(outer, list):
return
for row in outer:
@@ -107,25 +299,32 @@ def _chunks_from_outer(outer: Any) -> Iterator[Any]:
continue
inner = row[2]
if not isinstance(inner, str) or not inner:
- # Payload-less row: Google declined the call and parked an error
- # code in slot 5. Raise instead of yielding nothing, so callers
- # don't report a hard block as "no flights on this route".
- code = row[5][0] if len(row) > 5 and isinstance(row[5], list) and row[5] else None
- if isinstance(code, int):
- from fli.search.exceptions import SearchRejectedError
-
- raise SearchRejectedError(code)
+ status = _error_status(row)
+ if status is not None:
+ yield _ROW_ERROR, status
continue
try:
- yield json.loads(inner)
- except (ValueError, json.JSONDecodeError) as exc:
+ payload = json.loads(inner)
+ except (ValueError, RecursionError) as exc:
+ # ``RecursionError`` for pathologically nested inner JSON; it is
+ # a ``RuntimeError``, so ``ValueError`` alone would let it out.
logger.warning("Failed to decode wrb.fr inner JSON payload: %s", exc)
logger.debug("wrb.fr inner JSON decode failed", exc_info=True)
continue
+ yield _ROW_CHUNK, payload
def parse_first_wrb_payload(body: str | bytes) -> Any:
- """Return the inner JSON of the first ``wrb.fr`` chunk, or None."""
+ """Return the inner JSON of the first ``wrb.fr`` chunk, or None.
+
+ An error row trailing a usable chunk never raises: the first chunk is
+ returned and the generator is abandoned. See :func:`iter_wrb_chunks`.
+
+ Raises:
+ SearchRejectedError: If Google answered with an error envelope and
+ no usable chunk at all.
+
+ """
for chunk in iter_wrb_chunks(body):
return chunk
return None
diff --git a/fli/search/exceptions.py b/fli/search/exceptions.py
index 8e559a6..3e92063 100644
--- a/fli/search/exceptions.py
+++ b/fli/search/exceptions.py
@@ -30,6 +30,29 @@ class SearchHTTPError(SearchClientError):
self.status_code = status_code
+# Google reports a rejected request with gRPC's canonical status codes, so
+# the bare number can be named instead of left for the reader to look up.
+_GRPC_STATUS_NAMES = {
+ 0: "OK",
+ 1: "CANCELLED",
+ 2: "UNKNOWN",
+ 3: "INVALID_ARGUMENT",
+ 4: "DEADLINE_EXCEEDED",
+ 5: "NOT_FOUND",
+ 6: "ALREADY_EXISTS",
+ 7: "PERMISSION_DENIED",
+ 8: "RESOURCE_EXHAUSTED",
+ 9: "FAILED_PRECONDITION",
+ 10: "ABORTED",
+ 11: "OUT_OF_RANGE",
+ 12: "UNIMPLEMENTED",
+ 13: "INTERNAL",
+ 14: "UNAVAILABLE",
+ 15: "DATA_LOSS",
+ 16: "UNAUTHENTICATED",
+}
+
+
class SearchRejectedError(SearchClientError):
"""Google answered HTTP 200 but declined to serve results.
@@ -39,17 +62,32 @@ class SearchRejectedError(SearchClientError):
over the exact request bytes, so a plain HTTP client always lands here.
Without this error the caller saw an empty list and reported "no
flights found", which is indistinguishable from a route with no service.
+
+ A richer rejection carries a status message and/or a ``google.rpc``-style
+ detail block after the code, kept verbatim (truncated) in ``detail`` —
+ the code alone is often too coarse to debug with. An ``INTERNAL`` (13),
+ for instance, can mean either "Google declined to serve this" or "a
+ required request header was missing", and only the detail tells the two
+ apart.
"""
- def __init__(self, code: int | None = None):
- """Record the numeric error code alongside the user-facing message."""
+ def __init__(self, code: int | None = None, *, detail: str | None = None):
+ """Record the status code, its gRPC name and any detail block."""
self.code = code
- suffix = f" (error {code})" if code is not None else ""
- super().__init__(
+ self.detail = detail
+ self.status_name = _GRPC_STATUS_NAMES.get(code) if code is not None else None
+ named = f"{code} ({self.status_name})" if self.status_name else code
+ # ``0`` is gRPC's OK, so there is no error number to name — it reads
+ # the same as no code at all rather than claiming "error 0".
+ suffix = f" with error {named}" if code else ""
+ message = (
f"Google Flights declined the request{suffix} and returned no data. "
"Its API now requires a browser-signed x-goog-batchexecute-bgr header, "
"which this client cannot produce. See github.com/punitarani/fli#223."
)
+ if detail:
+ message = f"{message} Details: {detail}"
+ super().__init__(message)
class SearchUnsupportedError(SearchClientError):
diff --git a/tests/search/test_booking_options.py b/tests/search/test_booking_options.py
index 4ec72b8..5826300 100644
--- a/tests/search/test_booking_options.py
+++ b/tests/search/test_booking_options.py
@@ -253,6 +253,99 @@ class TestGetBookingOptionsErrorPaths:
assert opts == []
+class TestGetBookingOptionsRejectionEnvelope:
+ """A declined booking call must not read as "no bookable fares".
+
+ Google answers a request it refuses with ``HTTP 200`` and a payload-less
+ ``wrb.fr`` row carrying a gRPC status. That used to yield zero chunks,
+ which is indistinguishable from an itinerary nobody sells — so the wire
+ reader raises :class:`SearchRejectedError` instead, and it has to reach
+ the caller through ``get_booking_options`` unchanged.
+ """
+
+ @staticmethod
+ def _canned(body: str):
+ """Return a client plus a patch making its booking POST answer ``body``.
+
+ ``sf.client`` is a process-wide singleton, so the patch is handed
+ back as a context manager rather than started here — a leaked patch
+ feeds this canned body to every later test.
+ """
+ from unittest.mock import patch
+
+ def _fake_post(url, data, **kwargs): # noqa: ANN001
+ return type(
+ "R",
+ (),
+ {
+ "content": body.encode("utf-8"),
+ "text": body,
+ "raise_for_status": lambda self: None,
+ },
+ )()
+
+ sf = SearchFlights()
+ sf._last_session_id = "S"
+ return sf, patch.object(sf.client, "post", side_effect=_fake_post)
+
+ def test_error_envelope_raises_instead_of_returning_no_options(self):
+ """HTTP 200 + error envelope surfaces the status code, not an empty list."""
+ from fli.search import SearchRejectedError
+
+ body = ")]}'\n\n" + json.dumps(
+ [
+ ["wrb.fr", None, None, None, None, [13]],
+ ["di", 39],
+ ["af.httprm", 38, "-1963517503", 5],
+ ]
+ )
+ filters = _round_trip_filters()
+ flight = filters.flight_segments[1].selected_flight
+ sf, patcher = self._canned(body)
+ with patcher, pytest.raises(SearchRejectedError, match=r"13 \(INTERNAL\)") as excinfo:
+ sf.get_booking_options(flight, filters, currency="USD")
+ assert excinfo.value.code == 13
+
+ def test_rejection_reaches_the_cli_and_mcp_friendly_messages(self, monkeypatch, tmp_path):
+ """The typed error stays classified, not an "unexpected error"."""
+ from fli.cli.errors import _friendly_message, json_error_payload
+ from fli.core.errors import classify_error
+ from fli.mcp.server import _search_error_message
+ from fli.search import SearchRejectedError
+
+ # ``json_error_payload`` writes a real traceback file. Send it to
+ # tmp_path instead of the user's ~/.fli/logs, the way the autouse
+ # fixture in tests/cli/test_errors.py does for the same helper.
+ log_dir = tmp_path / "fli-logs"
+ monkeypatch.setattr("fli.cli.errors._LOG_DIR", log_dir)
+
+ exc = SearchRejectedError(13, detail="req-abc123")
+ assert "declined the request" in _friendly_message(exc)
+ assert "Unexpected error" not in _friendly_message(exc)
+ assert "declined the request" in _search_error_message(exc)
+
+ # Both surfaces classify it through the shared classifier, so they
+ # have to agree — a rejection is deterministic and never retryable.
+ payload = json_error_payload(exc, command="flights")
+ assert payload.error_type == "rejected_error"
+ assert payload.retryable is False
+ mcp_fields = classify_error(exc).as_fields()
+ assert mcp_fields["error_type"] == "rejected_error"
+ assert mcp_fields["retryable"] is False
+
+ assert list(log_dir.iterdir()), "the log file should have landed under tmp_path"
+
+ def test_genuinely_empty_response_still_returns_no_options(self):
+ """A well-formed response with no vendor rows keeps returning []."""
+ inner = json.dumps([[], None], separators=(",", ":"))
+ body = ")]}'\n\n" + json.dumps([["wrb.fr", None, inner]])
+ filters = _round_trip_filters()
+ flight = filters.flight_segments[1].selected_flight
+ sf, patcher = self._canned(body)
+ with patcher:
+ assert sf.get_booking_options(flight, filters, currency="USD") == []
+
+
class TestEncodeBookingPayloadValidation:
"""``_encode_booking_payload`` rejects filters that can't produce a main struct."""
diff --git a/tests/search/test_wire.py b/tests/search/test_wire.py
index 4e60f60..7c3b36f 100644
--- a/tests/search/test_wire.py
+++ b/tests/search/test_wire.py
@@ -1,10 +1,12 @@
"""Tests for the wire-format parser shared by all FlightsFrontendService responses."""
import json
+import logging
+import time
import pytest
-from fli.search._wire import iter_wrb_chunks, parse_first_wrb_payload
+from fli.search._wire import _CHUNK_BOUNDARY, iter_wrb_chunks, parse_first_wrb_payload
from fli.search.exceptions import SearchRejectedError
@@ -16,20 +18,22 @@ def _single_chunk(payload):
def _multi_chunk(*payloads):
- """Build a multi-chunk response with explicit length prefixes.
+ """Build a multi-chunk response with byte-counted length prefixes.
- Mirrors Google's actual format: each length header counts both the
- leading newline that follows the header AND the trailing newline that
- separates this chunk from the next (i.e. ``len(outer_json) + 1``).
+ Each length header counts the chunk plus its two surrounding newlines,
+ measured in UTF-8 bytes. Google measures in characters instead (see
+ :func:`_google_framed`); both helpers exist so the reader is pinned as
+ working under either convention.
+
+ ``json.dumps`` escapes non-ASCII by default, so the bodies this builds
+ are pure ASCII and the two counts coincide in them. The byte count is
+ exercised against a genuinely multi-byte body in
+ ``TestNonAsciiFraming.test_byte_counted_framing_of_the_same_body_also_parses``.
"""
parts = [")]}'\n\n"]
for p in payloads:
inner_json = json.dumps(p, separators=(",", ":"))
outer_json = json.dumps([["wrb.fr", None, inner_json]], separators=(",", ":"))
- # The length header counts UTF-8 BYTES (not Python str chars) plus
- # the two surrounding newlines. Encoding the JSON before measuring
- # keeps the test correct when payloads contain non-ASCII characters
- # like accented airport names or Japanese carrier strings.
byte_len = len(outer_json.encode("utf-8")) + 2
parts.append(f"{byte_len}\n{outer_json}\n")
return "".join(parts)
@@ -60,9 +64,7 @@ class TestIterWrbChunks:
assert list(iter_wrb_chunks(body)) == []
def test_non_ascii_chunk_payload(self):
- # The length header counts UTF-8 bytes, not characters — confirm a
- # payload with multi-byte chars round-trips correctly (regression
- # guard for the byte-vs-char-length bug in the test helper).
+ # Multi-byte payloads round-trip under the byte-counted framing.
body = _multi_chunk([1, "東京", "café", "résumé"])
chunks = list(iter_wrb_chunks(body))
assert chunks == [[1, "東京", "café", "résumé"]]
@@ -146,6 +148,687 @@ class TestParseFirstWrbPayloadEdgeCases:
assert parse_first_wrb_payload(body) == [42]
+def _google_framed(*payloads: object) -> str:
+ """Build a multi-chunk response framed the way Google actually frames it.
+
+ Measured on a live August 2026 ``GetShoppingResults`` response whose
+ airport names carry accents: the length header counts the chunk *plus
+ its two surrounding newlines*, in **characters**. On an ASCII-only
+ response that is indistinguishable from a byte count, which is why the
+ checked-in fixtures never exercised the difference.
+ """
+ parts = [")]}'\n\n"]
+ for p in payloads:
+ inner_json = json.dumps(p, separators=(",", ":"), ensure_ascii=False)
+ outer_json = json.dumps(
+ [["wrb.fr", None, inner_json]], separators=(",", ":"), ensure_ascii=False
+ )
+ parts.append(f"{len(outer_json) + 2}\n{outer_json}\n")
+ return "".join(parts)
+
+
+def _error_envelope(code: int) -> str:
+ """Build the HTTP 200 error envelope Google returns for a rejected request."""
+ outer = [
+ ["wrb.fr", None, None, None, None, [code]],
+ ["di", 39],
+ ["af.httprm", 38, "-1963517503", 5],
+ ]
+ return ")]}'\n\n" + json.dumps(outer, separators=(",", ":"))
+
+
+def _error_status_row(status: object) -> list[object]:
+ """Build a payload-less ``wrb.fr`` row carrying an arbitrary status field."""
+ return ["wrb.fr", None, None, None, None, status]
+
+
+def _rows_body(*rows: object) -> str:
+ """Wrap already-built outer rows into a single-chunk response body."""
+ return ")]}'\n\n" + json.dumps(list(rows), separators=(",", ":"))
+
+
+def _payload_row(payload: object) -> list[object]:
+ """Build a normal ``wrb.fr`` row carrying an inner JSON payload."""
+ return ["wrb.fr", None, json.dumps(payload, separators=(",", ":"))]
+
+
+def _malformed_chunks(count: int) -> str:
+ """Build a header-framed body whose every chunk fails to decode.
+
+ Each chunk fails at a fixed, tiny offset into itself, so the number of
+ decode failures equals ``count`` and the only thing that grows is how
+ far into the body each failure happens.
+ """
+ chunk = "[not json]"
+ parts = [")]}'\n\n"]
+ parts.extend(f"{len(chunk) + 2}\n{chunk}\n" for _ in range(count))
+ return "".join(parts)
+
+
+def _crlf_framed_chunks(count: int) -> str:
+ """Build valid chunks framed with CRLF headers.
+
+ The boundary pattern is newline-based, so a CRLF body carries no
+ boundary the reader can find — which is exactly the shape that must
+ not degrade into a per-chunk scan to the end of the document.
+ """
+ parts = [")]}'\r\n\r\n"]
+ for index in range(count):
+ chunk = json.dumps([_payload_row([index])], separators=(",", ":"))
+ parts.append(f"{len(chunk) + 2}\r\n{chunk}\r\n")
+ return "".join(parts)
+
+
+def _back_to_back_chunks(count: int) -> str:
+ """Build valid chunks with no length headers and nothing between them."""
+ parts = [")]}'\n\n"]
+ parts.extend(
+ json.dumps([_payload_row([index])], separators=(",", ":")) for index in range(count)
+ )
+ return "".join(parts)
+
+
+def _trailing_boundary_chunks(count: int) -> str:
+ """Build header-less chunks whose only boundary sits at the very end.
+
+ The worst case for the decode window: the region between the cursor and
+ the next boundary spans the whole body, so re-slicing it once per chunk
+ copies the entire remainder every time.
+ """
+ parts = [")]}'\n\n"]
+ parts.extend(
+ json.dumps([_payload_row([index])], separators=(",", ":")) for index in range(count)
+ )
+ last = json.dumps([_payload_row([count])], separators=(",", ":"))
+ parts.append(f"\n{len(last) + 2}\n{last}\n")
+ return "".join(parts)
+
+
+def _sparse_boundary_chunks(count: int, spacing: int | None = None) -> str:
+ """Build header-less chunks carrying a length header only every ``spacing``.
+
+ The same hazard with several regions instead of one. ``spacing``
+ defaults to a third of the body so the *regions* grow with it: at a
+ fixed spacing the per-chunk copy is only a constant factor (the
+ re-reviewer measured 1.2x at 1000 chunks per region, 2.2x at 5000),
+ which no ratio test can see. Only a region that grows with the body
+ turns it back into a curve.
+ """
+ if spacing is None:
+ spacing = max(count // 3, 1)
+ parts = [")]}'\n\n"]
+ for index in range(count):
+ # Wider payloads than the other shapes on purpose: the cost of the
+ # defect is (chunks x region bytes), so a region has to be big in
+ # BYTES for the copy to outweigh Python's per-chunk overhead. Fixed
+ # width, so the body grows exactly with ``count``.
+ chunk = json.dumps([_payload_row([index, "x" * 200])], separators=(",", ":"))
+ if index and index % spacing == 0:
+ parts.append(f"\n{len(chunk) + 2}\n")
+ parts.append(chunk)
+ return "".join(parts)
+
+
+def _newline_separated_chunks(count: int) -> str:
+ """Build valid chunks with no length headers, one newline between them."""
+ body = "\n".join(
+ json.dumps([_payload_row([index])], separators=(",", ":")) for index in range(count)
+ )
+ return ")]}'\n\n" + body
+
+
+def _sized_body(megabytes: float) -> str:
+ """Build a valid two-chunk body of roughly ``megabytes`` characters."""
+ # ~37 characters per element, so the row count sets the size directly.
+ rows = int(megabytes * 1_000_000 / 37)
+ return _google_framed(["Aéroport de Paris-Charles de Gaulle"] * rows, [1, "beta"])
+
+
+def _elapsed_over_body(body: str, repeats: int = 3) -> float:
+ """Return the fastest of ``repeats`` full reads of ``body``, in seconds."""
+ best = float("inf")
+ for _ in range(repeats):
+ started = time.perf_counter()
+ list(iter_wrb_chunks(body))
+ best = min(best, time.perf_counter() - started)
+ return best
+
+
+def _elapsed_quietly(body: str) -> float:
+ """Time a full read of ``body`` with this module's logger silenced.
+
+ Logging is a per-bad-chunk cost of its own; silencing it keeps a
+ timing measurement about the reader rather than about whatever
+ handler happens to be attached to the root logger.
+ """
+ logger = logging.getLogger("fli.search._wire")
+ previous = logger.level
+ logger.setLevel(logging.CRITICAL)
+ try:
+ return _elapsed_over_body(body)
+ finally:
+ logger.setLevel(previous)
+
+
+def _assert_scales_linearly(shape, sizes: tuple[int, int, int], label: str) -> str:
+ """Assert 4x the work costs well under 4x^2 the time, and describe the run.
+
+ Linear is ~4x for 4x the work and quadratic is ~16x, so the bound sits
+ between them and nowhere near either — a noisy box cannot cross it.
+ """
+ small, medium, large = (_elapsed_quietly(shape(size)) for size in sizes)
+ ratio = large / max(small, 1e-6)
+ timings = f"{small * 1000:.1f} / {medium * 1000:.1f} / {large * 1000:.1f} ms"
+ assert ratio < 8, f"{label}: 4x the work took {ratio:.1f}x the time ({timings}) — not linear"
+ return f"{label}: {timings} ({ratio:.2f}x)"
+
+
+class TestNonAsciiFraming:
+ """Chunks must survive non-ASCII payloads (issue: 'No flights found')."""
+
+ def test_accented_single_chunk_is_not_dropped(self):
+ payload = [None, None, [[["Aéroport de Paris-Charles de Gaulle", "Düsseldorf"]]]]
+ assert parse_first_wrb_payload(_google_framed(payload)) == payload
+
+ def test_accented_chunk_does_not_desync_the_stream(self):
+ body = _google_framed([1, "Aéroport de Paris-Charles de Gaulle"], [2, "beta"])
+ assert list(iter_wrb_chunks(body)) == [
+ [1, "Aéroport de Paris-Charles de Gaulle"],
+ [2, "beta"],
+ ]
+
+ def test_ascii_chunks_still_parse(self):
+ body = _google_framed([1, "Paris Charles de Gaulle Airport"], [2, "beta"])
+ assert list(iter_wrb_chunks(body)) == [
+ [1, "Paris Charles de Gaulle Airport"],
+ [2, "beta"],
+ ]
+
+ def test_byte_counted_framing_of_the_same_body_also_parses(self):
+ # The other plausible reading of the header: UTF-8 bytes. ``_multi_chunk``
+ # covers the byte count too, but ``json.dumps`` escapes non-ASCII by
+ # default, so its bodies are pure ASCII and the two counts coincide
+ # there. This builds the raw multi-byte body and announces its byte
+ # length, which is what pins the reader as correct under either
+ # convention rather than merely under Google's.
+ payloads = ([1, "Aéroport de Paris-Charles de Gaulle"], [2, "Düsseldorf"])
+ parts = [")]}'\n\n"]
+ for payload in payloads:
+ inner_json = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
+ outer_json = json.dumps(
+ [["wrb.fr", None, inner_json]], separators=(",", ":"), ensure_ascii=False
+ )
+ parts.append(f"{len(outer_json.encode('utf-8')) + 2}\n{outer_json}\n")
+ body = "".join(parts)
+ # The two conventions really do disagree on this body.
+ assert len(body.encode("utf-8")) != len(body)
+ assert list(iter_wrb_chunks(body)) == list(payloads)
+
+ def test_length_header_is_not_trusted(self):
+ # A header that matches neither the byte nor the character length
+ # must not affect decoding: chunk boundaries come from the JSON
+ # grammar, not from the announced length.
+ inner_json = json.dumps([1, "café"], separators=(",", ":"), ensure_ascii=False)
+ outer_json = json.dumps(
+ [["wrb.fr", None, inner_json]], separators=(",", ":"), ensure_ascii=False
+ )
+ body = f")]}}'\n\n999999\n{outer_json}\n1\n{outer_json}\n"
+ assert list(iter_wrb_chunks(body)) == [[1, "café"], [1, "café"]]
+
+
+class TestGrammarDelimitingRobustness:
+ """The JSON grammar — not the announced length — has to find every edge."""
+
+ def test_payload_strings_may_contain_framing_characters(self):
+ # Brackets, quotes and backslashes inside a string must not be
+ # mistaken for structure: json.dumps escapes them, and the reader
+ # relies on the decoder rather than scanning for "[" itself.
+ payload = [
+ 'a "quoted" [bracket] value',
+ 'back\\slash and \\" escaped quote',
+ "accented é with a ] and a newline\nin the middle",
+ ]
+ body = _google_framed(payload, [2, "beta"])
+ assert list(iter_wrb_chunks(body)) == [payload, [2, "beta"]]
+
+ def test_chunk_survives_a_boundary_that_falls_mid_string(self):
+ # The announced length cuts each chunk in half, in the middle of a
+ # string that itself contains "[". A length-slicing reader hands
+ # json.loads a truncated document and loses the rest of the body.
+ payload = [1, "x[" * 40]
+ inner_json = json.dumps(payload, separators=(",", ":"))
+ outer_json = json.dumps([["wrb.fr", None, inner_json]], separators=(",", ":"))
+ half = len(outer_json) // 2
+ body = f")]}}'\n\n{half}\n{outer_json}\n{half}\n{outer_json}\n"
+ assert list(iter_wrb_chunks(body)) == [payload, payload]
+
+ def test_garbage_between_chunks_is_skipped(self):
+ good_1 = json.dumps([_payload_row([1, "alpha"])], separators=(",", ":"))
+ good_2 = json.dumps([_payload_row([2, "beta"])], separators=(",", ":"))
+ body = (
+ f")]}}'\n\n{len(good_1) + 2}\n{good_1}\n"
+ "<<not json at all>>\n"
+ f"{len(good_2) + 2}\n{good_2}\n"
+ )
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"], [2, "beta"]]
+
+ def test_truncated_final_chunk_is_skipped_with_one_concise_warning(self, caplog):
+ # A transfer cut short must not hang, and must not raise out of the
+ # generator — the chunks that did arrive are still delivered.
+ good = json.dumps([_payload_row([1, "alpha"])], separators=(",", ":"))
+ truncated = json.dumps([_payload_row([2, "beta"])], separators=(",", ":"))[:-12]
+ body = f")]}}'\n\n{len(good) + 2}\n{good}\n{len(truncated) + 2}\n{truncated}"
+ with caplog.at_level(logging.WARNING, logger="fli.search._wire"):
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"]]
+ warnings = [r for r in caplog.records if r.levelno >= logging.WARNING]
+ assert len(warnings) == 1
+ assert "malformed wrb.fr chunk" in warnings[0].getMessage()
+ # Tracebacks belong at debug level, not in the operator's log.
+ assert warnings[0].exc_info is None
+
+ def test_pathologically_nested_chunk_does_not_escape_the_iterator(self, caplog):
+ # 20k unclosed brackets exhaust the decoder's recursion budget.
+ # ``RecursionError`` is a ``RuntimeError``, not a ``ValueError``, so
+ # it used to sail straight out of the generator and past every
+ # caller's ``except SearchClientError``.
+ nested = "[" * 20_000
+ good = json.dumps([_payload_row([1, "alpha"])], separators=(",", ":"))
+ body = f")]}}'\n\n{len(nested) + 2}\n{nested}\n{len(good) + 2}\n{good}\n"
+ with caplog.at_level(logging.WARNING, logger="fli.search._wire"):
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"]]
+ warnings = [r for r in caplog.records if r.levelno >= logging.WARNING]
+ assert len(warnings) == 1
+ assert warnings[0].exc_info is None
+
+ def test_deeply_nested_inner_payload_does_not_escape_either(self):
+ # Same hazard one level down: the inner JSON string is decoded by a
+ # separate ``json.loads`` inside the row walk.
+ body = _rows_body(["wrb.fr", None, "[" * 20_000], _payload_row([1, "alpha"]))
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"]]
+
+ def test_repeated_malformed_chunks_do_not_flood_the_log(self, caplog):
+ # One warning per bad chunk turns a garbage body into thousands of
+ # log lines. Warn on the first few, then summarise.
+ with caplog.at_level(logging.WARNING, logger="fli.search._wire"):
+ assert list(iter_wrb_chunks(_malformed_chunks(500))) == []
+ warnings = [r for r in caplog.records if r.levelno >= logging.WARNING]
+ assert len(warnings) <= 6, f"{len(warnings)} warning lines for 500 bad chunks"
+ assert "500" in warnings[-1].getMessage()
+
+ def test_valid_path_scales_linearly_with_body_size(self):
+ # The happy path must stay linear too. Kept to ~2 MB: a ratio over
+ # three sizes proves the shape without a multi-hundred-MB peak.
+ _assert_scales_linearly(_sized_body, (0.5, 1.0, 2.0), "header-framed valid, MB")
+
+
+class TestScalesLinearlyOnEveryBodyShape:
+ r"""Every framing shape must be O(n) — whatever the boundaries look like.
+
+ The reader looks ahead for the next ``\n<digits>\n[`` to bound each
+ decode, and there are two ways to make that per-chunk work instead of
+ per-region, both of which were real:
+
+ * a body with no boundary at all — CRLF framing, or chunks written back
+ to back with no length headers — makes the unmatched ``re.search``
+ scan to the end of the document once per chunk (a 2 MB CRLF body took
+ ~57 s against 69 ms for the reader that never looked ahead);
+ * a body whose boundaries are far apart makes the window *slice* copy
+ the whole remaining region once per chunk, which is the same shape of
+ cost without any search at all (80k chunks with one boundary at the
+ end copied ~105 GB and took 1.6 s against 81 ms).
+
+ Both are quadratic and neither shows up on the header-framed shape,
+ where every chunk has a boundary right behind it. Hence one ratio test
+ per shape rather than one for the format Google actually sends.
+ """
+
+ def test_header_framed_garbage(self):
+ # A failed decode must cost O(chunk), not O(offset-into-the-body):
+ # ``JSONDecodeError.__init__`` counts the newlines before the error
+ # position, so handing it the whole document once per bad chunk is
+ # quadratic too. Measured at ~4x per doubling before round 1.
+ _assert_scales_linearly(_malformed_chunks, (4_000, 8_000, 16_000), "header-framed garbage")
+
+ def test_crlf_framed_valid_chunks(self):
+ _assert_scales_linearly(_crlf_framed_chunks, (2_000, 4_000, 8_000), "CRLF-framed valid")
+
+ def test_back_to_back_header_less_valid_chunks(self):
+ _assert_scales_linearly(_back_to_back_chunks, (2_000, 4_000, 8_000), "back-to-back valid")
+
+ def test_newline_separated_header_less_valid_chunks(self):
+ _assert_scales_linearly(
+ _newline_separated_chunks, (2_000, 4_000, 8_000), "newline-separated valid"
+ )
+
+ def test_only_boundary_at_the_very_end(self):
+ # Worst case for the window slice: one boundary, at the end, so the
+ # region between cursor and boundary is the whole remaining body.
+ _assert_scales_linearly(
+ _trailing_boundary_chunks, (5_000, 10_000, 20_000), "trailing boundary only"
+ )
+
+ def test_sparse_boundaries(self):
+ # The same hazard at a realistic density — a header every 500 chunks.
+ _assert_scales_linearly(
+ _sparse_boundary_chunks, (5_000, 10_000, 20_000), "sparse boundaries"
+ )
+
+ def test_every_shape_still_decodes_every_chunk(self):
+ # Speed is worthless if the shapes stopped parsing. Pin the output
+ # of each one alongside its timing.
+ want = [[index] for index in range(50)]
+ assert list(iter_wrb_chunks(_crlf_framed_chunks(50))) == want
+ assert list(iter_wrb_chunks(_back_to_back_chunks(50))) == want
+ assert list(iter_wrb_chunks(_newline_separated_chunks(50))) == want
+ assert list(iter_wrb_chunks(_malformed_chunks(50))) == []
+ # The trailing-boundary shape carries one extra chunk after it.
+ assert list(iter_wrb_chunks(_trailing_boundary_chunks(50))) == [*want, [50]]
+ # The sparse shape carries a wider payload — see its builder.
+ assert list(iter_wrb_chunks(_sparse_boundary_chunks(50, spacing=10))) == [
+ [index, "x" * 200] for index in range(50)
+ ]
+
+
+# JSON fragments that could sit on either side of a boundary-shaped run of
+# characters if one could occur inside a chunk. Deliberately includes the
+# cases where "]" / "[" / quotes / escapes are content rather than syntax.
+_FRAGMENTS_BEFORE = (
+ "",
+ "[",
+ "[1",
+ "[1,",
+ "[[",
+ "[[1",
+ '["a"',
+ '["a",',
+ '["a\\"b"',
+ '["\\\\"',
+ '["]"',
+ '["["',
+ '["\\n"',
+ "{",
+ '{"k"',
+ '{"k":',
+ '{"k":1',
+ '{"k":1,',
+ '{"k":[',
+ "[true",
+ "[true,",
+ "[null,",
+ "[-1",
+ "[1.5",
+ "[1e5",
+ "[ ",
+ "[\t",
+ "[[],",
+ "[{},",
+ "[1,2",
+ "[1,2,",
+ '[{"a":1}',
+ '[{"a":1},',
+ "1",
+ "12",
+ "[0",
+ "[0,",
+)
+
+_FRAGMENTS_AFTER = (
+ "",
+ "]",
+ "]]",
+ "]]]",
+ "1]",
+ "1,2]",
+ '"a"]',
+ "]}",
+ "1]}",
+ ",2]",
+ "],",
+ "true]",
+ "null]",
+ "[]]",
+ "{}]",
+ '"]',
+ '\\"]',
+ '{"b":2}]',
+ " ]",
+ "\n]",
+)
+
+_BOUNDARY_SEPARATORS = (("\n", "\n"), ("\r\n", "\n"), ("\n", "\r\n"), ("\r\n", "\r\n"))
+
+_FRAGMENT_WRAPPERS = ("", "[", "[[", '{"k":[')
+
+
+class TestChunkBoundaryCannotSplitAValue:
+ """The load-bearing claim behind bounding each decode to a window.
+
+ ``_CHUNK_BOUNDARY`` is used to decide where the current chunk ends, so
+ the window is only safe if that pattern can never occur strictly inside
+ a value the decoder would accept. It cannot, by the JSON grammar: a raw
+ newline or carriage return is illegal unescaped inside a string, so the
+ digits would have to be a number token surrounded by whitespace — and a
+ number followed by ``[`` with only whitespace between them is not valid
+ JSON in any container (an array needs a comma, an object a comma or a
+ colon, and a top-level document ends after its one value).
+
+ Rather than leave that as prose, this enumerates boundary-shaped
+ strings wedged between JSON fragments and checks the decoder never
+ accepts a value reaching past the boundary.
+ """
+
+ def test_boundary_never_lands_inside_an_accepted_value(self):
+ decoder = json.JSONDecoder()
+ checked = 0
+ for wrapper in _FRAGMENT_WRAPPERS:
+ for before in _FRAGMENTS_BEFORE:
+ for first, second in _BOUNDARY_SEPARATORS:
+ head = wrapper + before + first + "1" + second + "["
+ for after in _FRAGMENTS_AFTER:
+ candidate = head + after
+ checked += 1
+ match = _CHUNK_BOUNDARY.search(candidate)
+ if match is None:
+ continue
+ try:
+ _, end = decoder.raw_decode(candidate, 0)
+ except (ValueError, RecursionError):
+ continue
+ assert end <= match.start(), (
+ f"a boundary at {match.start()} sits inside a value the "
+ f"decoder accepts out to {end}: {candidate!r}"
+ )
+ assert checked > 10_000
+
+
+class TestErrorEnvelope:
+ """Payload-less wrb.fr rows carry a status code and must not read as 'no results'."""
+
+ def test_internal_error_raises(self):
+ with pytest.raises(SearchRejectedError) as excinfo:
+ parse_first_wrb_payload(_error_envelope(13))
+ assert excinfo.value.code == 13
+ assert "13" in str(excinfo.value)
+ assert "INTERNAL" in str(excinfo.value)
+
+ def test_invalid_argument_raises(self):
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_error_envelope(3)))
+ assert excinfo.value.code == 3
+ assert "INVALID_ARGUMENT" in str(excinfo.value)
+
+ def test_unknown_code_still_raises_with_the_number(self):
+ with pytest.raises(SearchRejectedError) as excinfo:
+ parse_first_wrb_payload(_error_envelope(9999))
+ assert excinfo.value.code == 9999
+ assert "9999" in str(excinfo.value)
+
+ def test_payload_less_row_without_status_is_still_skipped(self):
+ # Short rows carry no status code — they stay a silent skip.
+ body = ")]}'\n\n" + json.dumps([["wrb.fr", None, None]])
+ assert list(iter_wrb_chunks(body)) == []
+
+ def test_ok_status_zero_is_not_an_error(self):
+ # 0 is gRPC's OK; it must not surface as "error 0".
+ assert list(iter_wrb_chunks(_rows_body(_error_status_row([0])))) == []
+
+ def test_boolean_status_is_not_an_error(self):
+ # bool subclasses int — True must not be read as error 1 (CANCELLED).
+ assert list(iter_wrb_chunks(_rows_body(_error_status_row([True])))) == []
+
+ def test_negative_status_is_not_an_error(self):
+ assert list(iter_wrb_chunks(_rows_body(_error_status_row([-1])))) == []
+
+
+class TestErrorEnvelopeDetail:
+ """The status may carry a message and detail block worth surfacing."""
+
+ def test_detail_block_reaches_the_exception(self):
+ # Shape captured live from GetExploreDestinations: the request id and
+ # type URL are the debugging hint, not the bare code.
+ status = [
+ 13,
+ None,
+ [
+ [
+ "type.googleapis.com/travel.frontend.flights.ErrorResponse",
+ [[None, None, 0, "req-abc123"], 0],
+ ]
+ ],
+ ]
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_rows_body(_error_status_row(status))))
+ assert excinfo.value.code == 13
+ assert "req-abc123" in excinfo.value.detail
+ assert "ErrorResponse" in excinfo.value.detail
+ assert "req-abc123" in str(excinfo.value)
+
+ def test_status_message_is_surfaced(self):
+ status = [7, "missing x-same-domain header"]
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_rows_body(_error_status_row(status))))
+ assert excinfo.value.detail == "missing x-same-domain header"
+ assert "missing x-same-domain header" in str(excinfo.value)
+
+ def test_bare_code_has_no_detail(self):
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_error_envelope(13)))
+ assert excinfo.value.detail is None
+
+ def test_oversized_detail_is_truncated(self):
+ status = [13, None, [["type.googleapis.com/x", ["y" * 5000]]]]
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_rows_body(_error_status_row(status))))
+ assert len(excinfo.value.detail) == 200
+ assert excinfo.value.detail.endswith("…")
+
+ def test_oversized_status_message_is_truncated(self):
+ # The message half of the status is Google-controlled text of any
+ # length. Uncapped it reached the exception string, the warning
+ # record and, through the CLI reporter, a file under ~/.fli/logs.
+ status = [13, "M" * 5_000_000]
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_rows_body(_error_status_row(status))))
+ assert len(excinfo.value.detail) <= 200
+ assert excinfo.value.detail.endswith("…")
+ assert len(str(excinfo.value)) < 1_000
+
+ def test_oversized_message_and_block_together_stay_bounded(self):
+ status = [13, "M" * 5_000_000, [["type.googleapis.com/x", ["y" * 5_000_000]]]]
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(_rows_body(_error_status_row(status))))
+ assert len(excinfo.value.detail) <= 200
+ assert len(str(excinfo.value)) < 1_000
+
+ def test_oversized_message_does_not_reach_the_log_record(self, caplog):
+ # Trailing error + a usable chunk is the one path that logs the
+ # detail instead of raising it.
+ status = [13, "M" * 5_000_000]
+ body = _rows_body(_payload_row([1, "alpha"]), _error_status_row(status))
+ with caplog.at_level(logging.WARNING, logger="fli.search._wire"):
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"]]
+ warnings = [r for r in caplog.records if r.levelno >= logging.WARNING]
+ assert len(warnings) == 1
+ assert len(warnings[0].getMessage()) < 1_000
+
+
+class TestSearchRejectedErrorRendering:
+ """The exception is built from Google-controlled input; it has to read sanely."""
+
+ def test_zero_is_grpc_ok_so_no_error_number_is_claimed(self):
+ # 0 is gRPC's OK. `_wire` never raises it, but a direct caller can,
+ # and "declined the request with error 0" is nonsense.
+ exc = SearchRejectedError(0)
+ assert exc.code == 0
+ assert exc.status_name == "OK"
+ assert "error 0" not in str(exc)
+ assert "declined the request and returned no data" in str(exc)
+
+ def test_no_code_reads_the_same_as_before(self):
+ assert "with error" not in str(SearchRejectedError())
+
+ def test_named_code_is_spelled_out(self):
+ assert "with error 13 (INTERNAL)" in str(SearchRejectedError(13))
+
+ def test_unknown_code_keeps_the_bare_number(self):
+ assert "with error 9999 and" in str(SearchRejectedError(9999))
+
+
+class TestErrorEnvelopeWithPartialResults:
+ """A TRAILING error row must not destroy chunks Google already sent."""
+
+ def test_error_after_a_valid_chunk_keeps_the_chunk(self):
+ body = _rows_body(_payload_row([1, "alpha"]), _error_status_row([13]))
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"]]
+
+ def test_error_before_a_valid_chunk_raises(self):
+ # Position DOES decide the outcome. An error row that arrives
+ # before any usable payload means the request itself was rejected;
+ # returning the chunks behind it would hand the caller a partial
+ # vendor list under a stderr warning nobody reads.
+ body = _rows_body(_error_status_row([13]), _payload_row([1, "alpha"]))
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(body))
+ assert excinfo.value.code == 13
+
+ def test_error_before_a_valid_chunk_raises_for_parse_first_too(self):
+ body = _rows_body(_error_status_row([13]), _payload_row([1, "alpha"]))
+ with pytest.raises(SearchRejectedError):
+ parse_first_wrb_payload(body)
+
+ def test_error_in_an_earlier_chunk_of_a_multi_chunk_body_raises(self):
+ # Same ruling across chunk boundaries, not just across rows.
+ bad = json.dumps([_error_status_row([13])], separators=(",", ":"))
+ good = json.dumps([_payload_row([1, "alpha"])], separators=(",", ":"))
+ body = f")]}}'\n\n{len(bad) + 2}\n{bad}\n{len(good) + 2}\n{good}\n"
+ with pytest.raises(SearchRejectedError):
+ list(iter_wrb_chunks(body))
+
+ def test_error_in_a_later_chunk_of_a_multi_chunk_body(self):
+ good = json.dumps([_payload_row([1, "alpha"])], separators=(",", ":"))
+ bad = json.dumps([_error_status_row([13])], separators=(",", ":"))
+ body = f")]}}'\n\n{len(good) + 2}\n{good}\n{len(bad) + 2}\n{bad}\n"
+ assert list(iter_wrb_chunks(body)) == [[1, "alpha"]]
+
+ def test_first_payload_is_returned_despite_a_trailing_error(self):
+ body = _rows_body(_payload_row([1, "alpha"]), _error_status_row([13]))
+ assert parse_first_wrb_payload(body) == [1, "alpha"]
+
+ def test_error_only_body_still_raises_for_both_consumers(self):
+ body = _rows_body(_error_status_row([13]))
+ with pytest.raises(SearchRejectedError):
+ list(iter_wrb_chunks(body))
+ with pytest.raises(SearchRejectedError):
+ parse_first_wrb_payload(body)
+
+ def test_undecodable_inner_json_does_not_count_as_a_chunk(self):
+ # The only payload row is unusable, so the error must still surface.
+ body = _rows_body(["wrb.fr", None, "{not valid"], _error_status_row([13]))
+ with pytest.raises(SearchRejectedError) as excinfo:
+ list(iter_wrb_chunks(body))
+ assert excinfo.value.code == 13
+
+
class TestPayloadLessRowIsRejection:
"""Google's gated RPC answers HTTP 200 with a payload-less row + error 13.