Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix(search): a date sweep that mostly failed to load raises instead of reporting no dates (#249)

Punit Arani74fa5506435c
diff --git a/CLAUDE.md b/CLAUDE.md
index e378715..bbde06c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -157,6 +157,13 @@ Consequences to keep in mind when changing search code:
the bound scales with `configure_concurrency`.
When it trips but prices still come back, `_collect` emits exactly one
warning naming the skipped count: a truncated answer must never be silent.
+- The breaker alone can't catch "1 loaded, 29 timeouts" — one loaded page,
+ even empty, disarms it for good. So `_collect` also raises when 0 priced
+ and at least half the attempted dates never loaded (`failed >= loaded`),
+ without the `FLI_SOCS_COOKIE` hint (a page did load, so it isn't a consent
+ wall). A minority of load failures with 0 results still returns `None`;
+ a minority alongside partial results still returns those results; both
+ log exactly one summary warning naming the counts.
- ~1 page in 60 arrives HTTP 200 with no `ds:1` blob. `fetch_payload` in
`fli/search/_tfs.py` is the single fetch path for both flights and dates and
retries exactly that case (`PAGE_FETCH_ATTEMPTS`, `PAGE_RETRY_BACKOFF`);
diff --git a/README.md b/README.md
index 216cf6a..9b671d5 100644
--- a/README.md
+++ b/README.md
@@ -197,7 +197,13 @@ What that means in practice:
own retries multiply in) and about 4 seconds, the same whether the range is 30
days or 93. Unbroken, a 93-date range would have cost 279 fetches and up to
837 requests. The bound is `(5 + worker count) x 3`, so raising
- `configure_concurrency` raises it proportionally.
+ `configure_concurrency` raises it proportionally. That breaker disarms for
+ good the moment any page loads, even an empty one, so it cannot catch a
+ sweep that is mostly timeouts around one lucky date — `SearchDates.search`
+ raises that case too, whenever nothing priced and at least half the
+ attempted dates never loaded. A minority of failures alongside real
+ results, or alongside a confirmed-empty range (`None`), still returns
+ normally but logs one warning naming the counts.
* **A page occasionally arrives without results.** Roughly one request in sixty
returns HTTP 200 with no `ds:1` blob; the client retries that case up to twice
(0.5s then 1.5s) before raising `SearchParseError`. A healthy search never
diff --git a/docs/typescript/quickstart.md b/docs/typescript/quickstart.md
index 7c4618e..218ec74 100644
--- a/docs/typescript/quickstart.md
+++ b/docs/typescript/quickstart.md
@@ -239,7 +239,12 @@ What that means in practice:
all of them. Ten dates are in flight at once, so around fourteen are
attempted first — about 42 page fetches, whether the range is 30, 61 or
93 days. One that was cut short but found prices returns them with a
- warning.
+ warning. That breaker disarms for good the moment any page loads, even
+ an empty one, so it cannot catch a sweep that is mostly timeouts around
+ one lucky date — `search` throws that case too, whenever nothing priced
+ and at least half the attempted dates never loaded. A minority of
+ failures alongside real results, or alongside a confirmed-empty range,
+ still returns normally but logs one warning naming the counts.
* **A page occasionally arrives without results.** Roughly one request in
sixty returns HTTP 200 with no `ds:1` blob; the client retries that case
up to twice (0.5s then 1.5s) before throwing `SearchParseError`.
diff --git a/fli-js/README.md b/fli-js/README.md
index aa0c59f..e1f6054 100644
--- a/fli-js/README.md
+++ b/fli-js/README.md
@@ -135,7 +135,14 @@ What that means in practice:
is 30, 61 or 93 days). Only pages served without results count towards that:
a timeout or a dropped connection says nothing about the dates not yet tried,
so those never abandon a sweep. A sweep cut short that still found prices
- returns them with one warning saying so.
+ returns them with one warning saying so. The breaker itself disarms for
+ good the moment any page loads, even an empty one — so it cannot catch a
+ sweep that is mostly timeouts around one lucky date. `SearchDates.search`
+ throws that case too: if nothing priced and at least half the attempted
+ dates never loaded, that is not enough evidence to call the range
+ flight-free. A minority of failures alongside real results, or alongside
+ a confirmed-empty range, still returns normally but logs one warning
+ naming the counts.
- **A page occasionally arrives without results.** Roughly one request in sixty
returns HTTP 200 with no `ds:1` blob; the client retries that case up to twice
(0.5s then 1.5s) before throwing `SearchParseError`. A healthy search never
diff --git a/fli-js/src/search/dates.ts b/fli-js/src/search/dates.ts
index faced93..57b668d 100644
--- a/fli-js/src/search/dates.ts
+++ b/fli-js/src/search/dates.ts
@@ -35,8 +35,12 @@ const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Same wording the flight path uses for the same condition, so a caller
* who sees it on either path gets the same hint about what to check.
+ *
+ * Exported (mirroring the Python module's `_NO_PAYLOAD`, importable despite
+ * the underscore) so tests can build `DateOutcome`s that exercise the
+ * no-payload branch of {@link SearchDates._collect} exactly.
*/
-const NO_PAYLOAD =
+export const NO_PAYLOAD =
"the search page carried no ds:1 payload — Google may have changed the " +
"page shape, or served a consent/blocked page instead";
@@ -214,6 +218,23 @@ function flightsIn(payload: unknown): FlightResult[] {
return flights;
}
+/**
+ * Up to 3 distinct failure messages, in the order they were first seen.
+ *
+ * Shared by every `_collect` branch that raises or warns about failed
+ * dates, so the same range always gets the same short list however it is
+ * reported.
+ */
+function reasonsFor(failed: DateOutcome[]): string[] {
+ const reasons: string[] = [];
+ for (const o of failed) {
+ if (o.failure != null && !reasons.includes(o.failure) && reasons.length < 3) {
+ reasons.push(o.failure);
+ }
+ }
+ return reasons;
+}
+
export class SearchDates {
/**
* @deprecated Kept only so the exported surface does not move. The
@@ -252,7 +273,9 @@ export class SearchDates {
* {@link MAX_DATES_PER_SEARCH} dates.
* @throws {SearchParseError} Every date came back without a payload —
* a consent or block page, not an empty route.
- * @throws {SearchClientError} Every date failed for some other reason.
+ * @throws {SearchClientError} Every date failed for some other reason,
+ * or nothing priced because at least half the attempted dates never
+ * loaded — see {@link SearchDates._collect}.
*/
async search(
filters: DateSearchFilters,
@@ -329,6 +352,20 @@ export class SearchDates {
* either. With prices to show, the answer is real but incomplete, so it
* comes with one warning naming the count.
*
+ * The breaker is not the only way a sweep can go quietly wrong, though:
+ * it disarms for good the instant any page loads, empty or not, so "1
+ * loaded, 29 timeouts" sails straight past it — one date out of thirty
+ * is not enough evidence that a route has no flights. When nothing
+ * priced and at least half the attempted dates never loaded (`failed
+ * >= loaded`), that is raised too. A page did load in that case, which
+ * rules out an EU/EEA consent wall — those block every request alike —
+ * so this path never adds the `FLI_SOCS_COOKIE` hint the branch above
+ * does.
+ *
+ * Short of either throw, a sweep that lost some dates but not enough to
+ * doubt the rest still owes the caller exactly one line saying so,
+ * whether or not it ends up with anything to return.
+ *
* Internal — underscore-prefixed rather than `private` so tests can
* drive it with a fixed set of outcomes instead of racing the sweep's
* concurrent fetches into the state they want to assert.
@@ -342,6 +379,11 @@ export class SearchDates {
const results = outcomes.flatMap((o) => (o.price != null ? [o.price] : []));
const attempted = outcomes.filter((o) => o.attempted);
const failed = attempted.filter((o) => o.failure != null);
+ // "loaded" counts every attempted date whose page actually arrived,
+ // priced or not — it does not distinguish the two, because when
+ // `results` is empty (the only time this number matters below) every
+ // loaded date is by definition one with no flights.
+ const loaded = attempted.length - failed.length;
// The breaker only ever trips on payload-less pages, so a non-zero
// skip count *is* the blocked-page diagnosis, whatever else failed
// alongside.
@@ -349,12 +391,7 @@ export class SearchDates {
const everythingFailed = attempted.length > 0 && failed.length === attempted.length;
if (results.length === 0 && (everythingFailed || tripped)) {
- const reasons: string[] = [];
- for (const o of failed) {
- if (o.failure != null && !reasons.includes(o.failure) && reasons.length < 3) {
- reasons.push(o.failure);
- }
- }
+ const reasons = reasonsFor(failed);
const cause = failed.find((o) => o.error != null)?.error;
const blocked =
tripped || (failed.length > 0 && failed.every((o) => o.failure === NO_PAYLOAD));
@@ -388,6 +425,27 @@ export class SearchDates {
throw new ErrorType(message, cause != null ? { cause } : undefined);
}
+ if (results.length === 0 && failed.length > 0 && failed.length >= loaded) {
+ // The breaker never saw this coming: one loaded page (even an empty
+ // one) disarms it for good, so a sweep that is mostly timeouts
+ // around a single lucky date never trips it. Half the attempted
+ // dates never loading is its own signal that "no flights" cannot be
+ // concluded from the handful that did.
+ const reasons = reasonsFor(failed);
+ const cause = failed.find((o) => o.error != null)?.error;
+ const blocked = failed.length > 0 && failed.every((o) => o.failure === NO_PAYLOAD);
+ const ErrorType = blocked ? SearchParseError : SearchClientError;
+ const message =
+ `Priced 0 of ${total} dates — ${failed.length} of the ${attempted.length} dates ` +
+ `tried failed to load, so "no flights" cannot be concluded from the ${loaded} ` +
+ `that did. Reasons: ${reasons.join("; ")}`;
+ // Unlike the branch above, a page did load here — that rules out a
+ // consent wall, which blocks every request identically. Adding the
+ // FLI_SOCS_COOKIE hint would point at a diagnosis this sweep just
+ // disproved, so it is deliberately left off.
+ throw new ErrorType(message, cause != null ? { cause } : undefined);
+ }
+
if (tripped) {
// Exactly one line, whatever the sweep's size: the caller is about
// to act on a partial answer and has no other way to know it.
@@ -397,6 +455,25 @@ export class SearchDates {
"had loaded yet. The prices below are real but incomplete — retry, or check " +
"FLI_SOCS_COOKIE if you are in the EU/EEA.",
);
+ } else if (failed.length > 0 && results.length > 0) {
+ // Neither throw fired — most dates loaded fine — but the caller
+ // still can't tell a complete sweep from this one just by looking
+ // at the list, so it gets the same "exactly one line" treatment.
+ getSearchLogger().warn(
+ `Date sweep priced ${results.length} of ${total} dates: ${failed.length} failed ` +
+ "to load. The prices below are real but incomplete.",
+ );
+ } else if (failed.length > 0) {
+ // No results, but too few dates failed to throw: most of the sweep
+ // loaded fine and simply found nothing. Still worth a line —
+ // otherwise a caller sees only `null`, indistinguishable from a
+ // sweep where every date loaded and truly had no flights.
+ const reasons = reasonsFor(failed);
+ getSearchLogger().warn(
+ `Date sweep found no flights on the ${loaded} dates that loaded; ${failed.length} ` +
+ `of ${attempted.length} dates failed to load, so treat this as provisional ` +
+ `rather than a confirmed empty range. Reasons: ${reasons.join("; ")}`,
+ );
}
return results.length > 0 ? results : null;
}
diff --git a/fli-js/tests/integration/search_dates_stubbed.test.ts b/fli-js/tests/integration/search_dates_stubbed.test.ts
index e948276..bf3ed2a 100644
--- a/fli-js/tests/integration/search_dates_stubbed.test.ts
+++ b/fli-js/tests/integration/search_dates_stubbed.test.ts
@@ -18,6 +18,7 @@ import { Client } from "../../src/search/client.ts";
import {
type DateOutcome,
MAX_DATES_PER_SEARCH,
+ NO_PAYLOAD,
SearchDates,
SWEEP_FAILURE_THRESHOLD,
} from "../../src/search/dates.ts";
@@ -88,6 +89,16 @@ function priced(price: number): DateOutcome {
};
}
+/** A `DateOutcome` whose page loaded with no flights, for driving `_collect` directly. */
+function loadedEmpty(): DateOutcome {
+ return { price: null, failure: null, error: null, attempted: true };
+}
+
+/** A `DateOutcome` for a date whose page never arrived, for driving `_collect` directly. */
+function failed(failure = "SearchConnectionError: connection refused"): DateOutcome {
+ return { price: null, failure, error: new Error(failure), attempted: true };
+}
+
function oneWayFilters(fromAhead: number, toAhead: number): DateSearchFilters {
const fromD = futureDate(fromAhead);
return new DateSearchFilters({
@@ -451,3 +462,149 @@ describe("SearchDates failure reporting", () => {
expect(warnings.filter((w) => w.includes("bags"))).toHaveLength(1);
});
});
+
+describe("SearchDates mostly-failed sweeps (T20)", () => {
+ // The breaker cannot catch "1 loaded, 29 timeouts": it disarms for good
+ // the moment any page loads, empty or not. If nothing priced and at least
+ // half the attempted dates never made it to a page, that is raised too —
+ // mirrors fli/search/dates.py's TestMostlyFailedSweepIsLoud.
+
+ test("mostly timeouts around one loaded empty date raises SearchClientError", () => {
+ const outcomes = [loadedEmpty(), ...Array.from({ length: 29 }, () => failed())];
+ let thrown: unknown;
+ try {
+ SearchDates._collect(outcomes, 30, 0);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(SearchClientError);
+ expect(thrown).not.toBeInstanceOf(SearchParseError);
+ const message = (thrown as Error).message;
+ expect(message).toContain("Priced 0 of 30");
+ expect(message).toContain("29 of the 30");
+ expect(message).not.toContain("FLI_SOCS_COOKIE");
+ expect((thrown as Error).cause).toBeInstanceOf(Error);
+ });
+
+ test("mostly no-payload failures raise SearchParseError without the SOCS hint", () => {
+ const outcomes = [loadedEmpty(), ...Array.from({ length: 3 }, () => failed(NO_PAYLOAD))];
+ let thrown: unknown;
+ try {
+ SearchDates._collect(outcomes, 4, 0);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(SearchParseError);
+ expect((thrown as Error).message).not.toContain("FLI_SOCS_COOKIE");
+ });
+
+ test("a tie between loaded and failed dates raises", () => {
+ const outcomes = [loadedEmpty(), failed()];
+ expect(() => SearchDates._collect(outcomes, 2, 0)).toThrow(SearchClientError);
+ });
+
+ test("a minority of failures with no results returns null and warns exactly once", () => {
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let results: ReturnType<typeof SearchDates._collect>;
+ try {
+ results = SearchDates._collect([loadedEmpty(), loadedEmpty(), loadedEmpty(), failed()], 4, 0);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(results).toBeNull();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain("3");
+ expect(warnings[0]).toContain("loaded");
+ expect(warnings[0]).toContain("1 of 4");
+ });
+
+ test("partial results with a minority failure warn exactly once", () => {
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let results: ReturnType<typeof SearchDates._collect>;
+ try {
+ results = SearchDates._collect([priced(100), priced(200), failed()], 3, 0);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(results).toHaveLength(2);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain("2 of 3");
+ });
+
+ test("partial results with a tripped breaker still warn exactly once", () => {
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let results: ReturnType<typeof SearchDates._collect>;
+ try {
+ results = SearchDates._collect(
+ [
+ priced(100),
+ ...Array.from({ length: 5 }, () => failed(NO_PAYLOAD)),
+ ...Array.from({ length: 24 }, () => ({
+ price: null,
+ failure: null,
+ error: null,
+ attempted: false,
+ })),
+ ],
+ 30,
+ 24,
+ );
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(results).toHaveLength(1);
+ expect(warnings).toHaveLength(1);
+ });
+
+ test("all loaded empty returns null with no warnings", () => {
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let results: ReturnType<typeof SearchDates._collect>;
+ try {
+ results = SearchDates._collect(
+ Array.from({ length: 5 }, () => loadedEmpty()),
+ 5,
+ 0,
+ );
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(results).toBeNull();
+ expect(warnings).toHaveLength(0);
+ });
+
+ test("all priced returns the list with no warnings", () => {
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let results: ReturnType<typeof SearchDates._collect>;
+ try {
+ results = SearchDates._collect(
+ Array.from({ length: 5 }, (_v, i) => priced(100 + i)),
+ 5,
+ 0,
+ );
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(results).toHaveLength(5);
+ expect(warnings).toHaveLength(0);
+ });
+
+ test("attempted:false outcomes are ignored by the new arithmetic", () => {
+ // 5 past dates + 1 loaded-empty + 1 failed must behave as the tie case.
+ const outcomes = [
+ ...Array.from({ length: 5 }, () => ({
+ price: null,
+ failure: null,
+ error: null,
+ attempted: false,
+ })),
+ loadedEmpty(),
+ failed(),
+ ];
+ expect(() => SearchDates._collect(outcomes, 7, 0)).toThrow(SearchClientError);
+ });
+});
diff --git a/fli/search/dates.py b/fli/search/dates.py
index 4f3a123..2a4a922 100644
--- a/fli/search/dates.py
+++ b/fli/search/dates.py
@@ -145,6 +145,20 @@ class _DateOutcome(NamedTuple):
attempted: bool = True
+def _reasons(failed: list[_DateOutcome]) -> list[str]:
+ """Up to 3 distinct failure messages, in the order they were first seen.
+
+ Shared by every ``_collect`` branch that raises or warns about failed
+ dates, so the same range always gets the same short list however it is
+ reported.
+ """
+ reasons: list[str] = []
+ for outcome in failed:
+ if outcome.failure not in reasons and len(reasons) < 3:
+ reasons.append(outcome.failure)
+ return reasons
+
+
def _flights_in(payload: Any) -> list[FlightResult]:
"""Decode every flight row in a ``ds:1`` payload.
@@ -211,7 +225,9 @@ class SearchDates:
Raises:
ValueError: The range covers more than :data:`MAX_DATES_PER_SEARCH`
dates, which would cost one page fetch each.
- SearchClientError: Every date in the range failed to load.
+ SearchClientError: Every date in the range failed to load, or
+ nothing priced because at least half the attempted dates
+ never loaded — see :meth:`_collect`.
Notes:
Every date in the range costs its own search-page fetch — the page
@@ -307,6 +323,20 @@ class SearchDates:
blocked — and the tripped breaker is the evidence for that, not the
exact mix of what each attempted date happened to do.
+ The breaker is not the only way a sweep can go quietly wrong, though:
+ it disarms for good the instant any page loads, empty or not, so "1
+ loaded, 29 timeouts" sails straight past it — one date out of thirty
+ is not enough evidence that a route has no flights. When nothing
+ priced and at least half the attempted dates never loaded (``failed
+ >= loaded``), that is raised too. A page did load in that case, which
+ rules out an EU/EEA consent wall — those block every request alike —
+ so this path never adds the ``FLI_SOCS_COOKIE`` hint the branch above
+ does.
+
+ Short of either raise, a sweep that lost some dates but not enough to
+ doubt the rest still owes the caller exactly one line saying so,
+ whether or not it ends up with anything to return.
+
Args:
outcomes: One entry per date in the range, in date order.
total: Dates the sweep set out to price, so the error can say how
@@ -318,16 +348,18 @@ class SearchDates:
results = [o.price for o in outcomes if o.price is not None]
attempted = [o for o in outcomes if o.attempted]
failed = [o for o in attempted if o.failure]
+ # "loaded" counts every attempted date whose page actually arrived,
+ # priced or not — it does not distinguish the two, because when
+ # ``results`` is empty (the only time this number matters below)
+ # every loaded date is by definition one with no flights.
+ loaded = len(attempted) - len(failed)
# The breaker only ever trips on payload-less pages, so a non-zero skip
# count *is* the blocked-page diagnosis, whatever else failed alongside.
tripped = skipped > 0
everything_failed = bool(attempted) and len(failed) == len(attempted)
if not results and (everything_failed or tripped):
- reasons: list[str] = []
- for outcome in failed:
- if outcome.failure not in reasons and len(reasons) < 3:
- reasons.append(outcome.failure)
+ reasons = _reasons(failed)
cause = next((o.error for o in failed if o.error is not None), None)
blocked = tripped or (bool(failed) and all(o.failure == _NO_PAYLOAD for o in failed))
error_type = SearchParseError if blocked else SearchClientError
@@ -359,6 +391,27 @@ class SearchDates:
)
raise error_type(message) from cause
+ if not results and failed and len(failed) >= loaded:
+ # The breaker never saw this coming: one loaded page (even an
+ # empty one) disarms it for good, so a sweep that is mostly
+ # timeouts around a single lucky date never trips it. Half the
+ # attempted dates never loading is its own signal that "no
+ # flights" cannot be concluded from the handful that did.
+ reasons = _reasons(failed)
+ cause = next((o.error for o in failed if o.error is not None), None)
+ blocked = bool(failed) and all(o.failure == _NO_PAYLOAD for o in failed)
+ error_type = SearchParseError if blocked else SearchClientError
+ message = (
+ f"Priced 0 of {total} dates — {len(failed)} of the {len(attempted)} dates "
+ f'tried failed to load, so "no flights" cannot be concluded from the '
+ f"{loaded} that did. Reasons: {'; '.join(reasons)}"
+ )
+ # Unlike the branch above, a page did load here — that rules out a
+ # consent wall, which blocks every request identically. Adding the
+ # FLI_SOCS_COOKIE hint would point at a diagnosis this sweep just
+ # disproved, so it is deliberately left off.
+ raise error_type(message) from cause
+
if tripped:
# Exactly one line, whatever the sweep's size: the caller is about
# to act on a partial answer and has no other way to know it.
@@ -372,6 +425,31 @@ class SearchDates:
skipped,
SWEEP_FAILURE_THRESHOLD,
)
+ elif failed and results:
+ # Neither raise fired — most dates loaded fine — but the caller
+ # still can't tell a complete sweep from this one just by looking
+ # at the list, so it gets the same "exactly one line" treatment.
+ logger.warning(
+ "Date sweep priced %d of %d dates: %d failed to load. The prices below "
+ "are real but incomplete.",
+ len(results),
+ total,
+ len(failed),
+ )
+ elif failed:
+ # No results, but too few dates failed to raise: most of the
+ # sweep loaded fine and simply found nothing. Still worth a line —
+ # otherwise a caller sees only `None`, indistinguishable from a
+ # sweep where every date loaded and truly had no flights.
+ logger.warning(
+ "Date sweep found no flights on the %d dates that loaded; %d of %d dates "
+ "failed to load, so treat this as provisional rather than a confirmed "
+ "empty range. Reasons: %s",
+ loaded,
+ len(failed),
+ len(attempted),
+ "; ".join(_reasons(failed)),
+ )
return results or None
def _build_chunk_filters(
diff --git a/tests/search/test_date_sweep.py b/tests/search/test_date_sweep.py
index 3081e79..f8d9367 100644
--- a/tests/search/test_date_sweep.py
+++ b/tests/search/test_date_sweep.py
@@ -721,3 +721,120 @@ class TestSweepCircuitBreaker:
with pytest.raises(SearchParseError) as excinfo:
_search_with(client).search(_filters(days=40))
assert "of 40 dates" in str(excinfo.value)
+
+
+# ---------------------------------------------------------------------------
+# A sweep that mostly failed to load must not read as "no flights" (T20)
+# ---------------------------------------------------------------------------
+
+
+class TestMostlyFailedSweepIsLoud:
+ """The breaker cannot catch "1 loaded, 29 timeouts" — it disarms for good
+ the moment any page loads, empty or not. If nothing priced and at least
+ half the attempted dates never made it to a page, that is raised too.
+ """ # noqa: D205
+
+ def _timeout(self) -> dates_module._DateOutcome:
+ return dates_module._DateOutcome(
+ failure="SearchConnectionError: connection refused",
+ error=SearchConnectionError("connection refused"),
+ )
+
+ def test_mostly_timeouts_around_one_loaded_empty_date_raises(self):
+ outcomes = [dates_module._DateOutcome(), *[self._timeout() for _ in range(29)]]
+ with pytest.raises(SearchClientError) as excinfo:
+ dates_module.SearchDates._collect(outcomes, 30, skipped=0)
+ assert not isinstance(excinfo.value, SearchParseError)
+ message = str(excinfo.value)
+ assert "Priced 0 of 30" in message, message
+ assert "29 of the 30" in message, message
+ assert "FLI_SOCS_COOKIE" not in message, message
+ assert isinstance(excinfo.value.__cause__, SearchConnectionError)
+
+ def test_mostly_no_payload_failures_raise_search_parse_error(self):
+ outcomes = [
+ dates_module._DateOutcome(),
+ *[dates_module._DateOutcome(failure=dates_module._NO_PAYLOAD) for _ in range(3)],
+ ]
+ with pytest.raises(SearchParseError) as excinfo:
+ dates_module.SearchDates._collect(outcomes, 4, skipped=0)
+ assert "FLI_SOCS_COOKIE" not in str(excinfo.value)
+
+ def test_tie_between_loaded_and_failed_raises(self):
+ outcomes = [dates_module._DateOutcome(), self._timeout()]
+ with pytest.raises(SearchClientError):
+ dates_module.SearchDates._collect(outcomes, 2, skipped=0)
+
+ def test_minority_failures_with_no_results_return_none_and_warn_once(self, caplog):
+ outcomes = [
+ dates_module._DateOutcome(),
+ dates_module._DateOutcome(),
+ dates_module._DateOutcome(),
+ self._timeout(),
+ ]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ results = dates_module.SearchDates._collect(outcomes, 4, skipped=0)
+ assert results is None
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ message = warnings[0].getMessage()
+ assert "3" in message and "loaded" in message, message
+ assert "1 of 4" in message, message
+
+ def test_partial_results_with_a_minority_failure_warns_once(self, caplog):
+ priced_a = dates_module.DatePrice(date=(FIRST_DAY,), price=100.0, currency="USD")
+ priced_b = dates_module.DatePrice(
+ date=(FIRST_DAY + timedelta(days=1),), price=200.0, currency="USD"
+ )
+ outcomes = [
+ dates_module._DateOutcome(price=priced_a),
+ dates_module._DateOutcome(price=priced_b),
+ self._timeout(),
+ ]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ results = dates_module.SearchDates._collect(outcomes, 3, skipped=0)
+ assert results == [priced_a, priced_b]
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert "2 of 3" in warnings[0].getMessage(), warnings[0].getMessage()
+
+ def test_partial_results_with_a_tripped_breaker_still_warns_once(self, caplog):
+ priced = dates_module.DatePrice(date=(FIRST_DAY,), price=100.0, currency="USD")
+ outcomes = [
+ dates_module._DateOutcome(price=priced),
+ *[dates_module._DateOutcome(failure=dates_module._NO_PAYLOAD) for _ in range(5)],
+ *[dates_module._DateOutcome(attempted=False) for _ in range(24)],
+ ]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ results = dates_module.SearchDates._collect(outcomes, 30, skipped=24)
+ assert results == [priced]
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+
+ def test_all_loaded_empty_returns_none_with_no_warnings(self, caplog):
+ outcomes = [dates_module._DateOutcome() for _ in range(5)]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ results = dates_module.SearchDates._collect(outcomes, 5, skipped=0)
+ assert results is None
+ assert not [r for r in caplog.records if r.levelno == logging.WARNING]
+
+ def test_all_priced_returns_list_with_no_warnings(self, caplog):
+ prices = [
+ dates_module.DatePrice(date=(FIRST_DAY + timedelta(days=i),), price=100.0 + i)
+ for i in range(5)
+ ]
+ outcomes = [dates_module._DateOutcome(price=p) for p in prices]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ results = dates_module.SearchDates._collect(outcomes, 5, skipped=0)
+ assert results == prices
+ assert not [r for r in caplog.records if r.levelno == logging.WARNING]
+
+ def test_not_attempted_dates_do_not_count_towards_the_arithmetic(self):
+ """5 past dates + 1 loaded-empty + 1 failed must behave as the tie case."""
+ outcomes = [
+ *[dates_module._DateOutcome(attempted=False) for _ in range(5)],
+ dates_module._DateOutcome(),
+ self._timeout(),
+ ]
+ with pytest.raises(SearchClientError):
+ dates_module.SearchDates._collect(outcomes, 7, skipped=0)