Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix: say so when children or infants are why a search came back empty (#255)

Punit Aranid925b0e8c90a
diff --git a/CLAUDE.md b/CLAUDE.md
index d3d41bc..fd4cb2a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -141,6 +141,20 @@ Consequences to keep in mind when changing search code:
offline and unaffected.
- A search returns fewer rows than the old RPC (~20-45), and client-side
filtering is not back-filled.
+- **Children and infants thin the results — sometimes to nothing.** Google
+ prices those parties client-side, so the page inlines fewer itineraries for
+ them, and in premium cabins often none (measured 2026-09: JFK→LHR economy
+ 23 rows for one adult, 16 with an infant; SFO→NRT business 9 rows for one
+ or two adults, 0 with a child). Extra adults cost nothing. An empty result
+ for such a search does not mean the route has no flights — and neither
+ does it mean this is why: `SearchFlights.search` / `SearchDates.search`
+ only warn (`SPARSE_PASSENGER_MIX_WARNING`) when the fetched page itself
+ came back with zero rows, not when the caller's own airline/price/
+ duration/window filter removed rows Google did return (see
+ `SearchFlights.sparse_passenger_mix`). The MCP `search_flights` empty
+ response carries the same text as `note`, and the CLI prints it under
+ "No flights found.", both reading that attribute rather than recomputing
+ the condition — an adults-only search shows the schedule.
- Date searches have no calendar grid: one page fetch per date, capped at
`fli.search.dates.MAX_DATES_PER_SEARCH` (93) per `SearchDates.search`. At the
cap that is several hundred MB of pages and parsed JSON at peak.
diff --git a/README.md b/README.md
index 191487e..3bc5ebe 100644
--- a/README.md
+++ b/README.md
@@ -190,6 +190,16 @@ What that means in practice:
* **Fewer rows per search.** Expect roughly 20-45 itineraries, fewer than the
old RPC returned — and a client-side filter cannot back-fill the list the way
Google's server-side one did.
+* **Children and infants thin the results — sometimes to nothing.** Google
+ prices those parties client-side, so the page inlines fewer itineraries for
+ them, and in premium cabins often none (measured 2026-09: JFK→LHR economy
+ 23 rows for one adult, 16 with an infant; SFO→NRT business 9 rows for one
+ or two adults, 0 with a child). Extra adults cost nothing. An empty result
+ for such a search does not mean the route has no flights — and neither
+ does it mean this is why: `search()` only warns when the fetched page
+ itself came back with zero rows, not when the caller's own airline/price/
+ duration/window filter removed rows Google did return. An adults-only
+ search shows the schedule.
* **Date searches cost one page fetch per date.** The page has no calendar
grid, so a range is priced date by date; one `SearchDates.search` covers at
most 93 dates and a wider range raises `ValueError`. Budget for it: 93 dates
diff --git a/docs/typescript/quickstart.md b/docs/typescript/quickstart.md
index 218ec74..d27378e 100644
--- a/docs/typescript/quickstart.md
+++ b/docs/typescript/quickstart.md
@@ -233,6 +233,16 @@ What that means in practice:
* **Fewer rows per search.** Expect roughly 20–45 itineraries, fewer than
the old RPC returned — and a client-side filter cannot back-fill the
list the way Google's server-side one did.
+* **Children and infants thin the results — sometimes to nothing.** Google
+ prices those parties client-side, so the page inlines fewer itineraries
+ for them, and in premium cabins often none (measured 2026-09: JFK→LHR
+ economy 23 rows for one adult, 16 with an infant; SFO→NRT business 9
+ rows for one or two adults, 0 with a child). Extra adults cost nothing.
+ An empty result for such a search does not mean the route has no
+ flights — and neither does it mean this is why: `search()` only warns
+ when the fetched page itself came back with zero rows, not when the
+ caller's own airline/price/duration/window filter removed rows Google
+ did return. An adults-only search shows the schedule.
* **Date searches cost one page fetch per date**, capped at 93 dates. A
sweep that never loads a single page stops once five dates have come
back payload-less and throws, rather than paying the retry budget on
diff --git a/fli-js/README.md b/fli-js/README.md
index e1f6054..90b7096 100644
--- a/fli-js/README.md
+++ b/fli-js/README.md
@@ -124,6 +124,16 @@ What that means in practice:
- **Fewer rows per search.** Expect roughly 20–45 itineraries, fewer than the
old RPC returned — and a client-side filter cannot back-fill the list the way
Google's server-side one did.
+- **Children and infants thin the results — sometimes to nothing.** Google
+ prices those parties client-side, so the page inlines fewer itineraries for
+ them, and in premium cabins often none (measured 2026-09: JFK→LHR economy
+ 23 rows for one adult, 16 with an infant; SFO→NRT business 9 rows for one
+ or two adults, 0 with a child). Extra adults cost nothing. An empty result
+ for such a search does not mean the route has no flights — and neither
+ does it mean this is why: `search()` only warns when the fetched page
+ itself came back with zero rows, not when the caller's own airline/price/
+ duration/window filter removed rows Google did return. An adults-only
+ search shows the schedule.
- **Date searches cost one page fetch per date.** The page has no calendar
grid, so a range is priced date by date; one `SearchDates.search` covers at
most 93 dates (`MAX_DATES_PER_SEARCH`) and a wider range throws `RangeError`.
diff --git a/fli-js/src/search/dates.ts b/fli-js/src/search/dates.ts
index 57b668d..b3f9415 100644
--- a/fli-js/src/search/dates.ts
+++ b/fli-js/src/search/dates.ts
@@ -12,7 +12,7 @@
*/
import { formatIsoDate, parseIsoDate } from "../core/dates.ts";
-import type { FlightResult } from "../models/google-flights/base.ts";
+import type { FlightResult, PassengerInfo } from "../models/google-flights/base.ts";
import { TripType } from "../models/google-flights/base.ts";
import type { DateSearchFilters } from "../models/google-flights/dates.ts";
import { type Client, getClient } from "./client.ts";
@@ -44,6 +44,29 @@ 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";
+/**
+ * Same wording `flights.ts` uses for the same condition — see
+ * {@link SPARSE_PASSENGER_MIX_WARNING} there for the live JFK-LHR / SFO-NRT
+ * row counts behind it. Duplicated rather than imported so this module's
+ * empty-result path stays self-contained.
+ */
+export const SPARSE_PASSENGER_MIX_WARNING =
+ "No itineraries were inlined for this passenger mix. Google's search page " +
+ "prices parties with children or infants client-side, so it often carries " +
+ "few or no rows for them — most of all in premium cabins. This does not " +
+ "mean the route has no flights: an adults-only search shows the schedule.";
+
+/**
+ * Whether the party includes anyone Google prices client-side.
+ *
+ * Extra adults ride the request for free; children and infants (lap or
+ * seat) are the passenger types that make the search-page transport inline
+ * fewer — sometimes zero — rows. See {@link SPARSE_PASSENGER_MIX_WARNING}.
+ */
+function hasChildrenOrInfants(passengerInfo: PassengerInfo): boolean {
+ return passengerInfo.children + passengerInfo.infants_on_lap + passengerInfo.infants_in_seat > 0;
+}
+
/**
* Most dates a single {@link SearchDates.search} call will price.
*
@@ -164,10 +187,29 @@ export interface DateOutcome {
error: unknown;
/** False for dates skipped before any request, so they don't count as failures. */
attempted: boolean;
+ /**
+ * How many rows the page decoded to *before* `applyClientSideFilters` ran,
+ * or `null`/absent when the page never loaded (`failure` is set) or the
+ * outcome was built by hand. Zero here means Google itself inlined
+ * nothing for the date; a positive count that still left `price` unset
+ * means the caller's own airline/price/duration/window filter removed
+ * every row — a different cause, so the two must not be conflated when
+ * deciding whether to blame a sparse passenger mix. Optional so existing
+ * hand-built ``DateOutcome`` literals (test fixtures predating this field)
+ * still type-check; an absent value reads the same as `null`.
+ */
+ rowsBeforeFilters?: number | null;
}
function outcome(over: Partial<DateOutcome> = {}): DateOutcome {
- return { price: null, failure: null, error: null, attempted: true, ...over };
+ return {
+ price: null,
+ failure: null,
+ error: null,
+ attempted: true,
+ rowsBeforeFilters: null,
+ ...over,
+ };
}
/** Midnight UTC today. */
@@ -253,11 +295,32 @@ export class SearchDates {
static readonly MAX_DATES_PER_SEARCH = MAX_DATES_PER_SEARCH;
private readonly client: Client;
+ private _sparsePassengerMix = false;
constructor(client?: Client) {
this.client = client ?? getClient();
}
+ /**
+ * Whether the sparse-passenger-mix warning fired on the most recent `search()`.
+ *
+ * `true` exactly when the empty sweep this instance last returned (or
+ * threw out of) was consistent with Google's client-side pricing gap for
+ * children/infants rather than the caller's own filters — see
+ * {@link SearchDates._warnIfSparsePassengerMix}. Reset to `false` at the
+ * start of every `search()` call, including ones that throw, so a stale
+ * `true` from an earlier call never leaks into a later one.
+ *
+ * Reflects only the *last completed* `search()` call on this instance and
+ * is not meant for instances shared across concurrent searches. Not
+ * currently read by any caller in this package (unlike
+ * {@link SearchFlights.sparsePassengerMix}); exposed here for symmetry
+ * with the warning this class already logs.
+ */
+ get sparsePassengerMix(): boolean {
+ return this._sparsePassengerMix;
+ }
+
/**
* Price every date in the filters' range.
*
@@ -281,6 +344,10 @@ export class SearchDates {
filters: DateSearchFilters,
options: DateSearchOptions = {},
): Promise<DatePrice[] | null> {
+ // Reset before anything below can throw, so a search that throws never
+ // leaves a stale true from an earlier call on this instance.
+ this._sparsePassengerMix = false;
+
throwIfAborted(options.signal);
const dropped = unsupportedFilters(filters);
@@ -328,7 +395,53 @@ export class SearchDates {
// not what happened.
throwIfAborted(options.signal);
- return SearchDates._collect(outcomes, tasks.length, health.skipped);
+ const result = SearchDates._collect(outcomes, tasks.length, health.skipped);
+ this._sparsePassengerMix = SearchDates._warnIfSparsePassengerMix(
+ outcomes,
+ result,
+ filters.passenger_info,
+ );
+ return result;
+ }
+
+ /**
+ * Warn once when an empty sweep may be Google's pricing gap, not a dead range.
+ *
+ * `_collect` already turns "every attempted date failed" or a tripped
+ * breaker into a throw, and a minority of load failures into its own
+ * summary warning (see its docstring) — so this only has something to add
+ * when nothing priced *and* not one attempted date failed to load.
+ *
+ * That alone is not enough, though: a date whose page loaded and decoded
+ * rows that the caller's own airline/price/duration/window filter then
+ * removed looks identical to one Google itself served nothing for, unless
+ * the pre-filter row count is checked too. Only when at least one loaded
+ * date's page decoded to *zero* rows before filtering is the emptiness
+ * actually Google's doing — see {@link DateOutcome.rowsBeforeFilters}. For
+ * a party with children or infants that is the shape Google's
+ * client-side pricing produces, not evidence the route has no service.
+ *
+ * Internal — underscore-prefixed rather than private, mirroring
+ * {@link SearchDates._collect}, so tests can drive it with a fixed set of
+ * outcomes instead of racing a real sweep's per-date failure logging into
+ * the state they want to assert.
+ *
+ * @returns Whether the warning fired — the caller mirrors this onto
+ * {@link SearchDates.sparsePassengerMix}.
+ */
+ static _warnIfSparsePassengerMix(
+ outcomes: DateOutcome[],
+ result: DatePrice[] | null,
+ passengerInfo: PassengerInfo,
+ ): boolean {
+ if (result != null) return false;
+ if (outcomes.some((o) => o.attempted && o.failure != null)) return false;
+ if (!outcomes.some((o) => o.attempted && o.failure == null && o.rowsBeforeFilters === 0)) {
+ return false;
+ }
+ if (!hasChildrenOrInfants(passengerInfo)) return false;
+ getSearchLogger().warn(SPARSE_PASSENGER_MIX_WARNING);
+ return true;
}
/** List every date in one chunk's `from_date`..`to_date` range. */
@@ -576,6 +689,7 @@ export class SearchDates {
);
let flights: FlightResult[];
+ let rawFlights: FlightResult[];
try {
const payload = await fetchPayload(this.client, url, { signal: options.signal });
if (payload == null) {
@@ -601,7 +715,14 @@ export class SearchDates {
// Decoding and filtering sit inside the `try` on purpose: they walk
// attacker-shaped data from the wire, and letting one odd row throw
// out of here would sink the whole sweep.
- flights = applyClientSideFilters(flightsIn(payload), filters);
+ //
+ // `rawFlights.length` is captured ahead of the filter call
+ // deliberately: it is what tells a genuinely empty Google page (0
+ // rows decoded) apart from a page Google filled that the caller's
+ // own airline/price/duration/window filter then emptied — see
+ // `DateOutcome.rowsBeforeFilters` and `_warnIfSparsePassengerMix`.
+ rawFlights = flightsIn(payload);
+ flights = applyClientSideFilters(rawFlights, filters);
} catch (err) {
// An in-flight date that was cancelled is not a failed date. Warning
// about it, counting it towards "every date failed", or feeding it
@@ -633,9 +754,10 @@ export class SearchDates {
cheapestPrice = flight.price;
}
}
- if (cheapest == null) return outcome();
+ if (cheapest == null) return outcome({ rowsBeforeFilters: rawFlights.length });
return outcome({
+ rowsBeforeFilters: rawFlights.length,
price: {
date: dates as [Date] | [Date, Date],
price: cheapestPrice,
diff --git a/fli-js/src/search/flights.ts b/fli-js/src/search/flights.ts
index 7dacddc..d05aa12 100644
--- a/fli-js/src/search/flights.ts
+++ b/fli-js/src/search/flights.ts
@@ -31,6 +31,61 @@ import {
import { withLocaleParams } from "./urls.ts";
import { iterWrbChunks } from "./wire.ts";
+/**
+ * Google inlines fewer rows — in premium cabins often none — for parties
+ * with children or infants, because those fares are priced client-side
+ * through the gated RPC this transport cannot reach; extra adults cost
+ * nothing. Measured live 2026-09-20: JFK-LHR economy held 23 rows for one
+ * adult and 16 with a lap infant; SFO-NRT business held 9 for one or two
+ * adults and 0 with a child.
+ */
+export const SPARSE_PASSENGER_MIX_WARNING =
+ "No itineraries were inlined for this passenger mix. Google's search page " +
+ "prices parties with children or infants client-side, so it often carries " +
+ "few or no rows for them — most of all in premium cabins. This does not " +
+ "mean the route has no flights: an adults-only search shows the schedule.";
+
+/**
+ * Whether the party includes anyone Google prices client-side.
+ *
+ * Extra adults ride the request for free; children and infants (lap or
+ * seat) are the passenger types that make the search-page transport inline
+ * fewer — sometimes zero — rows. See {@link SPARSE_PASSENGER_MIX_WARNING}.
+ */
+function hasChildrenOrInfants(passengerInfo: PassengerInfo): boolean {
+ return passengerInfo.children + passengerInfo.infants_on_lap + passengerInfo.infants_in_seat > 0;
+}
+
+/**
+ * Notes whether any fetched page decoded to zero rows before filtering.
+ *
+ * A round trip fetches the outbound page and then one page per expanded
+ * candidate (up to `topN`) as concurrent promises, so this is a fresh,
+ * per-{@link SearchFlights.search} object — never instance state. JavaScript
+ * runs those workers on one thread, so unlike the Python original this needs
+ * no lock, but it is still shared mutable state read after every worker's
+ * promise has settled, the same role `SweepHealth` plays in `dates.ts`.
+ *
+ * Distinguishes "Google itself inlined nothing" (rows === 0) from "Google
+ * inlined rows and the caller's own airline/price/duration/window filter
+ * removed every one of them" (rows > 0 but `applyClientSideFilters` emptied
+ * the list) — only the former is evidence of the sparse-passenger-mix
+ * pricing gap.
+ */
+class RowCountTracker {
+ private anyZero = false;
+
+ /** Note one page's decoded row count, before client-side filtering. */
+ record(rawRowCount: number): void {
+ if (rawRowCount === 0) this.anyZero = true;
+ }
+
+ /** Whether any recorded page decoded to zero rows. */
+ get anyZeroRows(): boolean {
+ return this.anyZero;
+ }
+}
+
/**
* Result ordering for `sortBy`.
*
@@ -118,11 +173,37 @@ export class SearchFlights {
private readonly client: Client;
private _lastSessionId: string | null = null;
+ private _sparsePassengerMix = false;
constructor(client?: Client) {
this.client = client ?? getClient();
}
+ /**
+ * Whether the sparse-passenger-mix warning fired on the most recent `search()`.
+ *
+ * `true` exactly when the empty result this instance last returned (or
+ * threw out of) was consistent with Google's client-side pricing gap for
+ * children/infants — at least one fetched page decoded to zero rows
+ * before client-side filtering, and the party had a child or infant —
+ * rather than the caller's own airline/price/duration/window filter
+ * removing rows Google did inline. See {@link SPARSE_PASSENGER_MIX_WARNING}.
+ * Reset to `false` at the start of every `search()` call, including ones
+ * that throw, so a stale `true` from an earlier call never leaks into a
+ * later one.
+ *
+ * Reflects only the *last completed* `search()` call on this instance and
+ * is not meant for instances shared across concurrent searches — two
+ * overlapping `search()` calls on one `SearchFlights` would race on this
+ * the same way they already race on the cached session id used by
+ * {@link SearchFlights.getBookingOptions}. Any MCP-equivalent or CLI-style
+ * caller should read this after `search()` instead of recomputing the
+ * condition itself.
+ */
+ get sparsePassengerMix(): boolean {
+ return this._sparsePassengerMix;
+ }
+
/**
* Search for flights using the given filters.
*
@@ -140,23 +221,60 @@ export class SearchFlights {
filters: FlightSearchFilters,
options: SearchOptions = {},
): Promise<Array<FlightResult | FlightResult[]> | null> {
+ // Reset before anything below can throw, so a search that throws never
+ // leaves a stale true from an earlier call on this instance.
+ this._sparsePassengerMix = false;
+
const topN = options.topN ?? 5;
+ // Per-search — never instance state, which the round trip's concurrent
+ // expansion workers (below) would trample mid-flight.
+ const tracker = new RowCountTracker();
const flights = await this._fetchFlights(filters, {
currency: options.currency ?? null,
language: options.language ?? null,
country: options.country ?? null,
captureSession: true,
signal: options.signal,
+ tracker,
});
- if (flights == null) return null;
+ if (flights == null) {
+ this._warnIfSparsePassengerMix(filters, tracker);
+ return null;
+ }
if (filters.trip_type === TripType.ONE_WAY) return flights;
- return this._expandMultiLeg(flights, filters, {
+ const combos = await this._expandMultiLeg(flights, filters, {
topN,
currency: options.currency ?? null,
language: options.language ?? null,
country: options.country ?? null,
signal: options.signal,
+ tracker,
});
+ if (combos.length === 0) this._warnIfSparsePassengerMix(filters, tracker);
+ return combos;
+ }
+
+ /**
+ * Warn once when an empty result may be Google's pricing gap, not a dead route.
+ *
+ * Called only from {@link SearchFlights.search}, after the trip's final
+ * result is known to be empty — never from {@link SearchFlights._fetchFlights},
+ * which the round-trip expansion calls once per candidate outbound. That
+ * keeps this to exactly one warning per `search` call, one-way or
+ * round-trip alike.
+ *
+ * `tracker` is what keeps this from misattributing an empty result: the
+ * final list can be empty either because Google inlined nothing
+ * (`tracker.anyZeroRows`) or because it inlined rows the caller's own
+ * airline/price/duration/window filter then removed entirely — the
+ * warning must only fire for the former.
+ */
+ private _warnIfSparsePassengerMix(filters: FlightSearchFilters, tracker: RowCountTracker): void {
+ if (!tracker.anyZeroRows) return;
+ if (hasChildrenOrInfants(filters.passenger_info)) {
+ this._sparsePassengerMix = true;
+ getSearchLogger().warn(SPARSE_PASSENGER_MIX_WARNING);
+ }
}
private async _fetchFlights(
@@ -167,6 +285,7 @@ export class SearchFlights {
country: string | null;
captureSession: boolean;
signal?: AbortSignal;
+ tracker?: RowCountTracker;
},
): Promise<FlightResult[] | null> {
throwIfAborted(opts.signal);
@@ -273,6 +392,7 @@ export class SearchFlights {
);
}
+ opts.tracker?.record(flights.length);
const kept = applyClientSideFilters(flights, filters);
sortFlights(kept, filters.sort_by);
return kept.length > 0 ? kept : null;
@@ -473,6 +593,7 @@ export class SearchFlights {
language: string | null;
country: string | null;
signal?: AbortSignal;
+ tracker?: RowCountTracker;
},
): Promise<Array<FlightResult[]>> {
const numSegments = filters.flight_segments.length;
@@ -495,6 +616,7 @@ export class SearchFlights {
country: opts.country,
captureSession: false,
signal: opts.signal,
+ tracker: opts.tracker,
});
if (subFlights == null) return [outbound, null];
if (selectedCount + 1 < numSegments - 1) {
diff --git a/fli-js/tests/integration/sparse_passenger_warning.test.ts b/fli-js/tests/integration/sparse_passenger_warning.test.ts
new file mode 100644
index 0000000..0e282e3
--- /dev/null
+++ b/fli-js/tests/integration/sparse_passenger_warning.test.ts
@@ -0,0 +1,642 @@
+/**
+ * Tests for the sparse-passenger-mix warning on empty results.
+ *
+ * Google's search-page transport inlines fewer (sometimes zero) rows for
+ * parties with children or infants — the fares are priced client-side
+ * through the gated RPC this transport cannot reach. An empty
+ * `SearchFlights.search` / `SearchDates.search` result for such a party used
+ * to be indistinguishable from a route with no service at all; these tests
+ * pin the one warning each call logs to explain the difference, and confirm
+ * it stays silent whenever it would not apply.
+ *
+ * A result can also come back empty because the *caller's own* client-side
+ * filter (airline, price cap, max duration, departure window) removed every
+ * row Google did inline — that is not evidence of the passenger-mix pricing
+ * gap, so a second family of tests below pins that the warning (and the
+ * `sparsePassengerMix` getter both classes expose) only fires when at least
+ * one fetched page decoded to zero rows *before* filtering.
+ *
+ * Mirrors tests/search/test_sparse_passenger_warning.py.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { Airline } from "../../src/models/airline.ts";
+import { Airport } from "../../src/models/airport.ts";
+import {
+ FlightSegment,
+ type PassengerInfo,
+ TripType,
+} from "../../src/models/google-flights/base.ts";
+import { DateSearchFilters } from "../../src/models/google-flights/dates.ts";
+import { FlightSearchFilters } from "../../src/models/google-flights/flights.ts";
+import { Client } from "../../src/search/client.ts";
+import {
+ SPARSE_PASSENGER_MIX_WARNING as DATES_SPARSE_WARNING,
+ type DateOutcome,
+ type DatePrice,
+ SearchDates,
+} from "../../src/search/dates.ts";
+import {
+ SPARSE_PASSENGER_MIX_WARNING as FLIGHTS_SPARSE_WARNING,
+ SearchFlights,
+} from "../../src/search/flights.ts";
+import { setSearchLogger } from "../../src/search/logging.ts";
+
+const ADULT_ONLY: PassengerInfo = {
+ adults: 2,
+ children: 0,
+ infants_in_seat: 0,
+ infants_on_lap: 0,
+};
+const WITH_CHILD: PassengerInfo = { adults: 1, children: 1, infants_in_seat: 0, infants_on_lap: 0 };
+
+function futureDate(daysAhead = 45): string {
+ const d = new Date();
+ d.setUTCDate(d.getUTCDate() + daysAhead);
+ return d.toISOString().slice(0, 10);
+}
+
+/** A minimal flight row `parseFlightRow` accepts. */
+function flightRow(price = 199.99, airlineCode = "DL"): unknown {
+ const leg: unknown[] = [
+ airlineCode,
+ null,
+ null,
+ "JFK",
+ null,
+ null,
+ "LAX",
+ null,
+ [12, 30],
+ null,
+ [16, 45],
+ 375,
+ null,
+ null,
+ null,
+ null,
+ null,
+ "Boeing 737",
+ null,
+ false,
+ [2026, 12, 25],
+ [2026, 12, 25],
+ [airlineCode, "100"],
+ ];
+ while (leg.length < 32) leg.push(null);
+ const detail: unknown[] = Array.from({ length: 25 }, () => null);
+ detail[0] = airlineCode;
+ detail[1] = ["Carrier"];
+ detail[2] = [leg];
+ detail[9] = 375;
+ const row: unknown[] = Array.from({ length: 11 }, () => null);
+ row[0] = detail;
+ row[1] = [[null, price], null];
+ return row;
+}
+
+function asSearchPage(payload: unknown): string {
+ return `<script>AF_initDataCallback({key: 'ds:1', hash: '1', data:${JSON.stringify(payload)}, sideChannel: {}});</script>`;
+}
+
+/** Wrap flight rows as a rendered search page (shared shape flights & dates both read). */
+function searchPage(rows: unknown[]): string {
+ const payload: unknown[] = Array.from({ length: 4 }, () => null);
+ payload[0] = [null, null, null, null, "test-session-id"];
+ payload[2] = [rows];
+ return asSearchPage(payload);
+}
+
+function oneWayFlightFilters(
+ passengerInfo: PassengerInfo,
+ overrides: Partial<ConstructorParameters<typeof FlightSearchFilters>[0]> = {},
+): FlightSearchFilters {
+ return new FlightSearchFilters({
+ passenger_info: passengerInfo,
+ flight_segments: [
+ new FlightSegment({
+ departure_airport: [[[Airport.JFK, 0]]],
+ arrival_airport: [[[Airport.LAX, 0]]],
+ travel_date: futureDate(),
+ }),
+ ],
+ ...overrides,
+ });
+}
+
+function roundTripFlightFilters(
+ passengerInfo: PassengerInfo,
+ overrides: Partial<ConstructorParameters<typeof FlightSearchFilters>[0]> = {},
+): FlightSearchFilters {
+ return new FlightSearchFilters({
+ trip_type: TripType.ROUND_TRIP,
+ passenger_info: passengerInfo,
+ flight_segments: [
+ new FlightSegment({
+ departure_airport: [[[Airport.JFK, 0]]],
+ arrival_airport: [[[Airport.LAX, 0]]],
+ travel_date: futureDate(45),
+ }),
+ new FlightSegment({
+ departure_airport: [[[Airport.LAX, 0]]],
+ arrival_airport: [[[Airport.JFK, 0]]],
+ travel_date: futureDate(52),
+ }),
+ ],
+ ...overrides,
+ });
+}
+
+function oneWayDateFilters(
+ days: number,
+ passengerInfo: PassengerInfo,
+ overrides: Partial<ConstructorParameters<typeof DateSearchFilters>[0]> = {},
+): DateSearchFilters {
+ const fromD = futureDate(30);
+ return new DateSearchFilters({
+ passenger_info: passengerInfo,
+ flight_segments: [
+ new FlightSegment({
+ departure_airport: [[[Airport.JFK, 0]]],
+ arrival_airport: [[[Airport.LAX, 0]]],
+ travel_date: fromD,
+ }),
+ ],
+ from_date: fromD,
+ to_date: futureDate(30 + days - 1),
+ ...overrides,
+ });
+}
+
+/** A Client whose fetch serves `bodies` in call order (last one repeats). */
+function clientServing(bodies: string[]): Client {
+ let calls = 0;
+ return new Client({
+ retries: 1,
+ fetchImpl: (async () => {
+ const body = bodies[Math.min(calls, bodies.length - 1)] as string;
+ calls++;
+ return new Response(body, { status: 200 });
+ }) as unknown as typeof fetch,
+ });
+}
+
+/**
+ * A Client whose response body can be swapped between calls, so the same
+ * SearchFlights/SearchDates instance can be reused across two searches —
+ * needed to test that `sparsePassengerMix` resets on the *same* instance
+ * (TS `Client` takes its `fetchImpl` once at construction, unlike Python's
+ * mutable `client.get`).
+ */
+function swappableClient(initialBody: string): { client: Client; setBody: (body: string) => void } {
+ let body = initialBody;
+ const client = new Client({
+ retries: 1,
+ backoffMs: 1,
+ fetchImpl: (async () => new Response(body, { status: 200 })) as unknown as typeof fetch,
+ });
+ return { client, setBody: (b: string) => (body = b) };
+}
+
+describe("SearchFlights sparse-passenger-mix warning", () => {
+ test("one-way empty result with a child warns exactly once", async () => {
+ const client = clientServing([searchPage([])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchFlights(client);
+ let result: unknown;
+ try {
+ result = await search.search(oneWayFlightFilters(WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toBe(FLIGHTS_SPARSE_WARNING);
+ expect(search.sparsePassengerMix).toBe(true);
+ });
+
+ test("one-way empty result, adults only, does not warn", async () => {
+ const client = clientServing([searchPage([])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchFlights(client);
+ let result: unknown;
+ try {
+ result = await search.search(oneWayFlightFilters(ADULT_ONLY));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("one-way non-empty result with a child does not warn", async () => {
+ const client = clientServing([searchPage([flightRow()])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let result: unknown;
+ try {
+ result = await new SearchFlights(client).search(oneWayFlightFilters(WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).not.toBeNull();
+ expect(warnings).toHaveLength(0);
+ });
+
+ test("round trip: outbound itself empty, child warns exactly once", async () => {
+ const client = clientServing([searchPage([])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let result: unknown;
+ try {
+ result = await new SearchFlights(client).search(roundTripFlightFilters(WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toBe(FLIGHTS_SPARSE_WARNING);
+ });
+
+ test("round trip: outbound has rows but every return-leg fetch is empty, child warns exactly once", async () => {
+ // `_fetchFlights` runs twice here (outbound + one expansion candidate);
+ // the warning must still fire only once for the whole `search()` call.
+ const client = clientServing([searchPage([flightRow()]), searchPage([])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let result: Array<unknown> | null;
+ try {
+ result = (await new SearchFlights(client).search(
+ roundTripFlightFilters(WITH_CHILD),
+ )) as Array<unknown> | null;
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result?.length ?? 0).toBe(0);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toBe(FLIGHTS_SPARSE_WARNING);
+ });
+
+ test("round trip: rows on both legs with a child does not warn", async () => {
+ const client = clientServing([searchPage([flightRow()]), searchPage([flightRow()])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let result: Array<unknown> | null;
+ try {
+ result = (await new SearchFlights(client).search(
+ roundTripFlightFilters(WITH_CHILD),
+ )) as Array<unknown> | null;
+ } finally {
+ setSearchLogger(null);
+ }
+ expect((result?.length ?? 0) > 0).toBe(true);
+ expect(warnings).toHaveLength(0);
+ });
+});
+
+describe("SearchFlights sparse-passenger-mix misattribution", () => {
+ // Every row here is on airline DL; filtering for AA removes it entirely —
+ // Google *did* inline something, so the sparse-mix diagnosis does not
+ // apply even though the final result is empty and the party has a child.
+
+ test("one-way: rows filtered out by airline does not warn", async () => {
+ const client = clientServing([searchPage([flightRow(199.99, "DL")])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchFlights(client);
+ let result: unknown;
+ try {
+ result = await search.search(oneWayFlightFilters(WITH_CHILD, { airlines: [Airline.AA] }));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("round trip: outbound rows filtered out does not warn", async () => {
+ // Never even reaches the return-leg fetch — the outbound leg's
+ // post-filter result is already empty.
+ const client = clientServing([searchPage([flightRow(199.99, "DL")])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchFlights(client);
+ let result: unknown;
+ try {
+ result = await search.search(roundTripFlightFilters(WITH_CHILD, { airlines: [Airline.AA] }));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("round trip: outbound survives, return-leg row filtered out does not warn", async () => {
+ // Outbound row matches the filter; the return-leg row does not. The
+ // return-leg page still carried a row (Google inlined it) — the
+ // caller's own filter removed it, not Google.
+ const client = clientServing([
+ searchPage([flightRow(199.99, "AA")]),
+ searchPage([flightRow(199.99, "DL")]),
+ ]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchFlights(client);
+ let result: Array<unknown> | null;
+ try {
+ result = (await search.search(
+ roundTripFlightFilters(WITH_CHILD, { airlines: [Airline.AA] }),
+ )) as Array<unknown> | null;
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result?.length ?? 0).toBe(0);
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+});
+
+describe("SearchFlights.sparsePassengerMix lifecycle", () => {
+ test("resets to false after a non-sparse search on the same instance", async () => {
+ const { client, setBody } = swappableClient(searchPage([]));
+ const search = new SearchFlights(client);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ try {
+ await search.search(oneWayFlightFilters(WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(search.sparsePassengerMix).toBe(true);
+
+ setBody(searchPage([flightRow()]));
+ const result = await search.search(oneWayFlightFilters(WITH_CHILD));
+ expect(result).not.toBeNull();
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("resets to false before a search that throws", async () => {
+ const { client, setBody } = swappableClient(searchPage([]));
+ const search = new SearchFlights(client);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ try {
+ await search.search(oneWayFlightFilters(WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(search.sparsePassengerMix).toBe(true);
+
+ setBody("<html><body>consent wall</body></html>");
+ setSearchLogger({ warn: () => {}, debug: () => {} });
+ try {
+ await expect(search.search(oneWayFlightFilters(WITH_CHILD))).rejects.toThrow();
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+});
+
+function priced(price: number): DateOutcome {
+ return {
+ price: { date: [new Date(2030, 0, 1)], price, currency: "USD" },
+ failure: null,
+ error: null,
+ attempted: true,
+ rowsBeforeFilters: 1,
+ };
+}
+
+function loadedEmptyRawZero(): DateOutcome {
+ return { price: null, failure: null, error: null, attempted: true, rowsBeforeFilters: 0 };
+}
+
+function loadedEmptyFilteredOut(rowsBeforeFilters = 2): DateOutcome {
+ return { price: null, failure: null, error: null, attempted: true, rowsBeforeFilters };
+}
+
+function failedOutcome(failure = "SearchConnectionError: transient"): DateOutcome {
+ return {
+ price: null,
+ failure,
+ error: new Error(failure),
+ attempted: true,
+ rowsBeforeFilters: null,
+ };
+}
+
+describe("SearchDates._warnIfSparsePassengerMix (unit)", () => {
+ test("no result, no failures, zero raw rows, child warns exactly once", () => {
+ const outcomes = [loadedEmptyRawZero(), loadedEmptyRawZero(), loadedEmptyRawZero()];
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let warned: boolean;
+ try {
+ warned = SearchDates._warnIfSparsePassengerMix(outcomes, null, WITH_CHILD);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toBe(DATES_SPARSE_WARNING);
+ expect(warned).toBe(true);
+ });
+
+ test("no result, no failures, adults only does not warn", () => {
+ const outcomes = [loadedEmptyRawZero(), loadedEmptyRawZero(), loadedEmptyRawZero()];
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let warned: boolean;
+ try {
+ warned = SearchDates._warnIfSparsePassengerMix(outcomes, null, ADULT_ONLY);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(warnings).toHaveLength(0);
+ expect(warned).toBe(false);
+ });
+
+ test("no result but a failed date present, child does not warn", () => {
+ // A failed date means `_collect` already explains the gap — the two
+ // warnings must never stack.
+ const outcomes = [
+ loadedEmptyRawZero(),
+ loadedEmptyRawZero(),
+ loadedEmptyRawZero(),
+ failedOutcome(),
+ ];
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let warned: boolean;
+ try {
+ warned = SearchDates._warnIfSparsePassengerMix(outcomes, null, WITH_CHILD);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(warnings).toHaveLength(0);
+ expect(warned).toBe(false);
+ });
+
+ test("a result present, child does not warn", () => {
+ const p = priced(150);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let warned: boolean;
+ try {
+ warned = SearchDates._warnIfSparsePassengerMix([p], [p.price as DatePrice], WITH_CHILD);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(warnings).toHaveLength(0);
+ expect(warned).toBe(false);
+ });
+
+ test("no result, rows filtered out every date, does not warn", () => {
+ // Every date's page carried rows; the caller's own filter emptied all.
+ const outcomes = [
+ loadedEmptyFilteredOut(2),
+ loadedEmptyFilteredOut(3),
+ loadedEmptyFilteredOut(1),
+ ];
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let warned: boolean;
+ try {
+ warned = SearchDates._warnIfSparsePassengerMix(outcomes, null, WITH_CHILD);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(warnings).toHaveLength(0);
+ expect(warned).toBe(false);
+ });
+
+ test("no result, mixed zero and filtered rows, still warns", () => {
+ // At least one date's page was genuinely empty — still the pricing gap.
+ const outcomes = [loadedEmptyFilteredOut(2), loadedEmptyRawZero()];
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let warned: boolean;
+ try {
+ warned = SearchDates._warnIfSparsePassengerMix(outcomes, null, WITH_CHILD);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(warnings).toHaveLength(1);
+ expect(warned).toBe(true);
+ });
+
+ test("1 failed + 3 empty + child: exactly one warning total, and it is the sweep's own", () => {
+ // Exercises `_collect` and `_warnIfSparsePassengerMix` together, in the
+ // same order `SearchDates.search` calls them, so the "cannot stack"
+ // contract between the two is pinned directly.
+ const outcomes = [
+ loadedEmptyRawZero(),
+ loadedEmptyRawZero(),
+ loadedEmptyRawZero(),
+ failedOutcome(),
+ ];
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ let result: DatePrice[] | null;
+ try {
+ result = SearchDates._collect(outcomes, 4, 0);
+ SearchDates._warnIfSparsePassengerMix(outcomes, result, WITH_CHILD);
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).not.toBe(DATES_SPARSE_WARNING);
+ expect(warnings[0]).toContain("loaded");
+ });
+});
+
+describe("SearchDates sparse-passenger-mix warning (integration, stubbed)", () => {
+ test("empty sweep with a child warns exactly once", async () => {
+ const client = clientServing([searchPage([])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchDates(client);
+ let result: DatePrice[] | null;
+ try {
+ result = await search.search(oneWayDateFilters(3, WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toBe(DATES_SPARSE_WARNING);
+ expect(search.sparsePassengerMix).toBe(true);
+ });
+
+ test("empty sweep, adults only, does not warn", async () => {
+ const client = clientServing([searchPage([])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchDates(client);
+ let result: DatePrice[] | null;
+ try {
+ result = await search.search(oneWayDateFilters(3, ADULT_ONLY));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("sweep with results, child, does not warn", async () => {
+ const client = clientServing([searchPage([flightRow()])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchDates(client);
+ let result: DatePrice[] | null;
+ try {
+ result = await search.search(oneWayDateFilters(3, WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).not.toBeNull();
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("sweep: rows filtered out by airline every date does not warn", async () => {
+ const client = clientServing([searchPage([flightRow(199.99, "DL")])]);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ const search = new SearchDates(client);
+ let result: DatePrice[] | null;
+ try {
+ result = await search.search(oneWayDateFilters(3, WITH_CHILD, { airlines: [Airline.AA] }));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(result).toBeNull();
+ expect(warnings).toHaveLength(0);
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+
+ test("sparsePassengerMix resets to false after a non-sparse sweep on the same instance", async () => {
+ const { client, setBody } = swappableClient(searchPage([]));
+ const search = new SearchDates(client);
+ const warnings: string[] = [];
+ setSearchLogger({ warn: (m) => warnings.push(m), debug: () => {} });
+ try {
+ await search.search(oneWayDateFilters(3, WITH_CHILD));
+ } finally {
+ setSearchLogger(null);
+ }
+ expect(search.sparsePassengerMix).toBe(true);
+
+ setBody(searchPage([flightRow()]));
+ const result = await search.search(oneWayDateFilters(3, WITH_CHILD));
+ expect(result).not.toBeNull();
+ expect(search.sparsePassengerMix).toBe(false);
+ });
+});
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index fcbff2f..b84e4a7 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -5,6 +5,7 @@ from typing import Annotated, Any
import typer
from pydantic import ValidationError
+from fli.cli.console import console
from fli.cli.enums import OutputFormat
from fli.cli.errors import json_error_payload, report_cli_error
from fli.cli.utils import (
@@ -40,6 +41,7 @@ from fli.models import (
TripType,
)
from fli.search import SearchClientError, SearchFlights
+from fli.search.flights import SPARSE_PASSENGER_MIX_WARNING
def _search_flights_core(
@@ -224,6 +226,16 @@ def _search_flights_core(
)
if not results:
+ # Read the library's own verdict rather than recomputing "empty +
+ # children/infants" here: SearchFlights.search already knows
+ # whether the empty result traces back to a page Google itself
+ # served with zero rows, versus the caller's own airline/price/
+ # duration/window filter removing rows Google did inline — that
+ # distinction lives in the fetch path, not in these arguments,
+ # so it can only be answered correctly once, there.
+ sparse_note = (
+ SPARSE_PASSENGER_MIX_WARNING if search_client.sparse_passenger_mix else None
+ )
if output_format == OutputFormat.JSON:
emit_json(
build_json_success_response(
@@ -233,11 +245,14 @@ def _search_flights_core(
results_key="flights",
results=[],
booking_url=booking_url,
+ note=sparse_note,
)
)
return
typer.echo("No flights found.")
+ if sparse_note:
+ console.print(sparse_note, style="dim", soft_wrap=True)
raise typer.Exit(1)
# Build per-flight booking deep-links (tfs; never raises).
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index abbb8c8..f99c3ba 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -346,8 +346,14 @@ def build_json_success_response(
results_key: str,
results: list[dict[str, Any]],
booking_url: str | None = None,
+ note: str | None = None,
) -> dict[str, Any]:
- """Build a JSON success payload for CLI commands."""
+ """Build a JSON success payload for CLI commands.
+
+ ``note`` is an optional explanatory string (e.g. the sparse-passenger-mix
+ hint on an empty result) — additive, like ``booking_url``, so callers that
+ don't pass it see no shape change.
+ """
payload: dict[str, Any] = {
"success": True,
"data_source": "google_flights",
@@ -359,6 +365,8 @@ def build_json_success_response(
}
if booking_url:
payload["booking_url"] = booking_url
+ if note:
+ payload["note"] = note
return payload
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 104c033..8f8ef67 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -47,6 +47,7 @@ from fli.models import (
)
from fli.search import SearchDates, SearchFlights
from fli.search.dates import MAX_DATES_PER_SEARCH
+from fli.search.flights import SPARSE_PASSENGER_MIX_WARNING
class FlightSearchConfig(BaseSettings):
@@ -725,13 +726,23 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
)
if not flights:
- return {
+ response: dict[str, Any] = {
"success": True,
"flights": [],
"count": 0,
"trip_type": trip_type.name,
"booking_url": booking_url,
}
+ # Read the library's own verdict rather than recomputing "empty +
+ # children/infants" here: SearchFlights.search already knows
+ # whether the empty result traces back to a page Google itself
+ # served with zero rows, versus the caller's own airline/price/
+ # duration/window filter removing rows Google did inline — that
+ # distinction lives in the fetch path, not in params, so it can
+ # only be answered correctly once, there.
+ if search_client.sparse_passenger_mix:
+ response["note"] = SPARSE_PASSENGER_MIX_WARNING
+ return response
# Serialize results; attach per-flight deep-link booking URL.
is_round_trip = trip_type == TripType.ROUND_TRIP
diff --git a/fli/search/dates.py b/fli/search/dates.py
index 2a4a922..9454d29 100644
--- a/fli/search/dates.py
+++ b/fli/search/dates.py
@@ -14,7 +14,7 @@ from typing import Any, NamedTuple
from pydantic import BaseModel
from fli.core import extract_currency_from_price_token
-from fli.models import DateSearchFilters, FlightResult
+from fli.models import DateSearchFilters, FlightResult, PassengerInfo
from fli.models.google_flights.base import TripType, earliest_searchable_date
from fli.search._concurrency import parallel_map
from fli.search._decoders import parse_flight_row
@@ -37,6 +37,30 @@ _NO_PAYLOAD = (
"page shape, or served a consent/blocked page instead"
)
+# Same wording ``fli.search.flights`` uses for the same condition — see
+# ``SPARSE_PASSENGER_MIX_WARNING`` there for the live JFK-LHR / SFO-NRT row
+# counts behind it. Duplicated rather than imported so this module's
+# empty-result path stays self-contained.
+SPARSE_PASSENGER_MIX_WARNING = (
+ "No itineraries were inlined for this passenger mix. Google's search page "
+ "prices parties with children or infants client-side, so it often carries "
+ "few or no rows for them — most of all in premium cabins. This does not "
+ "mean the route has no flights: an adults-only search shows the schedule."
+)
+
+
+def _has_children_or_infants(passenger_info: PassengerInfo) -> bool:
+ """Whether the party includes anyone Google prices client-side.
+
+ Extra adults ride the request for free; children and infants (lap or
+ seat) are the passenger types that make the search-page transport inline
+ fewer — sometimes zero — rows. See ``SPARSE_PASSENGER_MIX_WARNING``.
+ """
+ return (
+ passenger_info.children + passenger_info.infants_on_lap + passenger_info.infants_in_seat > 0
+ )
+
+
MAX_DATES_PER_SEARCH = 93
"""Most dates a single :meth:`SearchDates.search` call will price.
@@ -136,6 +160,14 @@ class _DateOutcome(NamedTuple):
error: The exception behind ``failure``, kept for chaining.
attempted: ``False`` for dates skipped before any request (past
dates), so they don't count towards the "everything failed" check.
+ rows_before_filters: How many rows the page decoded to *before*
+ ``apply_client_side_filters`` ran, or ``None`` when the page
+ never loaded (``failure`` is set). Zero here means Google itself
+ inlined nothing for the date; a positive count that still left
+ ``price`` unset means the caller's own airline/price/duration/
+ window filter removed every row — a different cause, so the two
+ must not be conflated when deciding whether to blame a sparse
+ passenger mix.
""" # noqa: D413
@@ -143,6 +175,7 @@ class _DateOutcome(NamedTuple):
failure: str | None = None
error: BaseException | None = None
attempted: bool = True
+ rows_before_filters: int | None = None
def _reasons(failed: list[_DateOutcome]) -> list[str]:
@@ -203,6 +236,29 @@ class SearchDates:
def __init__(self):
"""Initialize the search client for date-based searches."""
self.client = get_client()
+ # Set at the start of every search() call — see the
+ # sparse_passenger_mix property.
+ self._sparse_passenger_mix: bool = False
+
+ @property
+ def sparse_passenger_mix(self) -> bool:
+ """Whether the sparse-passenger-mix warning fired on the most recent search().
+
+ ``True`` exactly when the empty sweep this instance last returned (or
+ raised out of) was consistent with Google's client-side pricing gap
+ for children/infants rather than the caller's own filters — see
+ ``_warn_if_sparse_passenger_mix``. Reset to ``False`` at the start of
+ every :meth:`search` call, including ones that raise, so a stale
+ ``True`` from an earlier call never leaks into a later one.
+
+ Reflects only the *last completed* :meth:`search` call on this
+ instance and is not meant for instances shared across concurrent
+ searches — two overlapping :meth:`search` calls on one
+ ``SearchDates`` would race on this attribute. Not currently read by
+ the MCP server or CLI (unlike ``SearchFlights.sparse_passenger_mix``);
+ exposed here for symmetry with the warning this class already logs.
+ """
+ return self._sparse_passenger_mix
def search(
self,
@@ -237,6 +293,10 @@ class SearchDates:
priced by a single flat parallel map.
"""
+ # Reset before any code below can raise, so a search that raises
+ # never leaves a stale True from an earlier call on this instance.
+ self._sparse_passenger_mix = False
+
dropped = unsupported_filters(filters)
if dropped:
logger.warning(
@@ -288,7 +348,55 @@ class SearchDates:
),
tasks,
)
- return self._collect(outcomes, len(tasks), skipped=health.skipped)
+ result = self._collect(outcomes, len(tasks), skipped=health.skipped)
+ self._sparse_passenger_mix = self._warn_if_sparse_passenger_mix(
+ outcomes, result, filters.passenger_info
+ )
+ return result
+
+ @staticmethod
+ def _warn_if_sparse_passenger_mix(
+ outcomes: list[_DateOutcome],
+ result: list[DatePrice] | None,
+ passenger_info: PassengerInfo,
+ ) -> bool:
+ """Warn once when an empty sweep may be Google's pricing gap, not a dead range.
+
+ ``_collect`` already turns "every attempted date failed" or a tripped
+ breaker into a raise, and a minority of load failures into its own
+ summary warning (see its docstring) — so this only has something to
+ add when nothing priced *and* not one attempted date failed to load.
+
+ That alone is not enough, though: a date whose page loaded and
+ decoded rows that the caller's own airline/price/duration/window
+ filter then removed looks identical to one Google itself served
+ nothing for, unless the pre-filter row count is checked too. Only
+ when at least one loaded date's page decoded to *zero* rows before
+ filtering is the emptiness actually Google's doing — see
+ ``_DateOutcome.rows_before_filters``. For a party with children or
+ infants that is the shape Google's client-side pricing produces, not
+ evidence the route has no service.
+
+ Internal — underscore-prefixed rather than private, mirroring
+ :meth:`_collect`, so tests can drive it with a fixed set of outcomes
+ instead of racing a real sweep's per-date failure logging into the
+ state they want to assert.
+
+ Returns:
+ Whether the warning fired — the caller mirrors this onto
+ :attr:`SearchDates.sparse_passenger_mix`.
+
+ """
+ if result is not None:
+ return False
+ if any(o.failure for o in outcomes if o.attempted):
+ return False
+ if not any(o.rows_before_filters == 0 for o in outcomes if o.attempted and not o.failure):
+ return False
+ if not _has_children_or_infants(passenger_info):
+ return False
+ logger.warning(SPARSE_PASSENGER_MIX_WARNING)
+ return True
def _days_in(self, filters: DateSearchFilters) -> list[datetime]:
"""List every date in one chunk's ``from_date``..``to_date`` range."""
@@ -577,7 +685,14 @@ class SearchDates:
# walk attacker-shaped data from the wire, and letting one odd row
# raise out of here would sink the whole sweep, which is the class
# of bug this method exists to avoid.
- flights = apply_client_side_filters(_flights_in(payload), filters)
+ #
+ # ``rows_before_filters`` is captured ahead of the filter call
+ # deliberately: it is what tells a genuinely empty Google page
+ # (0 rows decoded) apart from a page Google filled that the
+ # caller's own airline/price/duration/window filter then emptied
+ # — see ``_DateOutcome`` and ``_warn_if_sparse_passenger_mix``.
+ raw_flights = _flights_in(payload)
+ flights = apply_client_side_filters(raw_flights, filters)
prices = [flight.price for flight in flights if flight.price]
except Exception as exc: # noqa: BLE001 — one bad date must not sink the sweep
# One concise line per bad date. A 93-date sweep against a blocked
@@ -593,14 +708,15 @@ class SearchDates:
return _DateOutcome(failure=f"{type(exc).__name__}: {exc}", error=exc)
if not prices:
- return _DateOutcome()
+ return _DateOutcome(rows_before_filters=len(raw_flights))
return _DateOutcome(
price=DatePrice(
date=tuple(dates),
price=min(prices),
currency=currency,
- )
+ ),
+ rows_before_filters=len(raw_flights),
)
@staticmethod
diff --git a/fli/search/flights.py b/fli/search/flights.py
index 70294cf..0340e44 100644
--- a/fli/search/flights.py
+++ b/fli/search/flights.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import logging
+import threading
import urllib.parse
from collections.abc import Callable
from copy import deepcopy
@@ -50,6 +51,66 @@ logger = logging.getLogger(__name__)
# ``SearchClientError`` and is classified as a search failure, not a crash.
__all__ = ["SearchFlights", "SearchParseError"]
+# Google inlines fewer rows — in premium cabins often none — for parties with
+# children or infants, because those fares are priced client-side through the
+# gated RPC this transport cannot reach; extra adults cost nothing. Shared
+# verbatim by the CLI's empty-result hint and the MCP `search_flights` empty
+# response's `note` field, so every surface explains an empty result the
+# same way. Measured live 2026-09-20: JFK-LHR economy held 23 rows for one
+# adult and 16 with a lap infant; SFO-NRT business held 9 for one or two
+# adults and 0 with a child.
+SPARSE_PASSENGER_MIX_WARNING = (
+ "No itineraries were inlined for this passenger mix. Google's search page "
+ "prices parties with children or infants client-side, so it often carries "
+ "few or no rows for them — most of all in premium cabins. This does not "
+ "mean the route has no flights: an adults-only search shows the schedule."
+)
+
+
+def _has_children_or_infants(passenger_info: PassengerInfo) -> bool:
+ """Whether the party includes anyone Google prices client-side.
+
+ Extra adults ride the request for free; children and infants (lap or
+ seat) are the passenger types that make the search-page transport inline
+ fewer — sometimes zero — rows. See ``SPARSE_PASSENGER_MIX_WARNING``.
+ """
+ return (
+ passenger_info.children + passenger_info.infants_on_lap + passenger_info.infants_in_seat > 0
+ )
+
+
+class _RowCountTracker:
+ """Notes whether any fetched page decoded to zero rows before filtering.
+
+ A round trip fetches the outbound page and then one page per expanded
+ candidate (up to ``top_n``) in parallel worker threads, so this is a
+ fresh, per-:meth:`SearchFlights.search` object — never instance state —
+ guarded by a lock the same way ``fli.search.dates._SweepHealth`` guards
+ its own cross-thread counters. Distinguishes "Google itself inlined
+ nothing" (rows == 0) from "Google inlined rows and the caller's own
+ airline/price/duration/window filter removed every one of them" (rows >
+ 0 but ``apply_client_side_filters`` emptied the list) — only the former
+ is evidence of the sparse-passenger-mix pricing gap.
+ """
+
+ __slots__ = ("_lock", "_any_zero_rows")
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._any_zero_rows = False
+
+ def record(self, raw_row_count: int) -> None:
+ """Note one page's decoded row count, before client-side filtering."""
+ if raw_row_count == 0:
+ with self._lock:
+ self._any_zero_rows = True
+
+ @property
+ def any_zero_rows(self) -> bool:
+ """Whether any recorded page decoded to zero rows."""
+ with self._lock:
+ return self._any_zero_rows
+
def _sort_key(sort_by: SortBy) -> Callable[[FlightResult], Any]:
"""Return the result-ordering key for ``sort_by``.
@@ -87,6 +148,8 @@ class SearchFlights:
:meth:`get_booking_options` can derive the booking token; two
concurrent ``search`` calls on the same instance will race on that
cache and may cross-pollinate sessions between unrelated bookings.
+ :attr:`sparse_passenger_mix` has the same limitation — it reflects
+ only the most recently *completed* :meth:`search` call.
For multi-threaded or async server use, either (a) instantiate a
fresh ``SearchFlights`` per request, or (b) pass the
@@ -116,6 +179,35 @@ class SearchFlights:
# :meth:`get_booking_options` can derive the booking token without
# the caller having to pass anything.
self._last_session_id: str | None = None
+ # Set at the start of every search() call — see the
+ # sparse_passenger_mix property.
+ self._sparse_passenger_mix: bool = False
+
+ @property
+ def sparse_passenger_mix(self) -> bool:
+ """Whether the sparse-passenger-mix warning fired on the most recent search().
+
+ ``True`` exactly when the empty result this instance last returned
+ (or raised out of) was consistent with Google's client-side pricing
+ gap for children/infants — at least one fetched page decoded to zero
+ rows before client-side filtering, and the party had a child or
+ infant — rather than the caller's own airline/price/duration/window
+ filter removing rows Google did inline. See
+ ``SPARSE_PASSENGER_MIX_WARNING``. Reset to ``False`` at the start of
+ every :meth:`search` call, including ones that raise, so a stale
+ ``True`` from an earlier call never leaks into a later one.
+
+ Reflects only the *last completed* :meth:`search` call on this
+ instance and is not meant for instances shared across concurrent
+ searches — two overlapping :meth:`search` calls on one
+ ``SearchFlights`` would race on this attribute the same way they
+ already race on ``_last_session_id`` (see the class docstring's
+ Concurrency section). The MCP server and CLI each construct a fresh
+ ``SearchFlights`` per request, so this is safe there; both read this
+ attribute after :meth:`search` instead of recomputing the condition
+ themselves.
+ """
+ return self._sparse_passenger_mix
# ------------------------------------------------------------------
# Public search API
@@ -160,6 +252,10 @@ class SearchFlights:
Exception: HTTP failure or unparseable response.
"""
+ # Reset before any code below can raise, so a search that raises
+ # never leaves a stale True from an earlier call on this instance.
+ self._sparse_passenger_mix = False
+
if not isinstance(top_n, int) or isinstance(top_n, bool) or not 1 <= top_n <= 10:
raise ValueError(
f"top_n must be an integer between 1 and 10 (inclusive); got {top_n!r} "
@@ -167,25 +263,56 @@ class SearchFlights:
"round-trip search expands into return-flight combinations — cost is "
"1 + top_n page fetches, hence the cap."
)
+ # Per-search, lock-guarded — never instance state, which the round
+ # trip's parallel expansion workers (below) would trample mid-flight.
+ tracker = _RowCountTracker()
flights = self._fetch_flights(
filters,
currency=currency,
language=language,
country=country,
capture_session=True,
+ tracker=tracker,
)
if flights is None:
+ self._warn_if_sparse_passenger_mix(filters, tracker)
return None
if filters.trip_type == TripType.ONE_WAY:
return flights
- return self._expand_multi_leg(
+ combos = self._expand_multi_leg(
flights,
filters,
top_n=top_n,
currency=currency,
language=language,
country=country,
+ tracker=tracker,
)
+ if not combos:
+ self._warn_if_sparse_passenger_mix(filters, tracker)
+ return combos
+
+ def _warn_if_sparse_passenger_mix(
+ self, filters: FlightSearchFilters, tracker: _RowCountTracker
+ ) -> None:
+ """Warn once when an empty result may be Google's pricing gap, not a dead route.
+
+ Called only from :meth:`search`, after the trip's final result is known
+ to be empty — never from :meth:`_fetch_flights`, which the round-trip
+ expansion calls once per candidate outbound. That keeps this to exactly
+ one warning per :meth:`search` call, one-way or round-trip alike.
+
+ ``tracker`` is what keeps this from misattributing an empty result:
+ the final list can be empty either because Google inlined nothing
+ (``tracker.any_zero_rows``) or because it inlined rows the caller's
+ own airline/price/duration/window filter then removed entirely — the
+ warning must only fire for the former.
+ """
+ if not tracker.any_zero_rows:
+ return
+ if _has_children_or_infants(filters.passenger_info):
+ self._sparse_passenger_mix = True
+ logger.warning(SPARSE_PASSENGER_MIX_WARNING)
def _fetch_flights(
self,
@@ -195,6 +322,7 @@ class SearchFlights:
language: str | None,
country: str | None,
capture_session: bool,
+ tracker: _RowCountTracker | None = None,
) -> list[FlightResult] | None:
"""Issue one ``GetShoppingResults`` call and decode the flight rows.
@@ -205,6 +333,12 @@ class SearchFlights:
not write to that field — both because the writes would race and
because the user-visible session id should describe the original
shopping query, not whichever expansion completed last.
+
+ ``tracker``, when given, records this page's decoded row count
+ *before* ``apply_client_side_filters`` runs — see
+ :class:`_RowCountTracker`. Optional because this method also backs
+ callers (tests, older shims) that don't care about the
+ sparse-passenger-mix diagnosis.
"""
dropped = unsupported_filters(filters)
if dropped:
@@ -262,6 +396,8 @@ class SearchFlights:
f"Google response shape may have changed (sample reasons: {sample})"
)
+ if tracker is not None:
+ tracker.record(len(flights))
flights = apply_client_side_filters(flights, filters)
flights.sort(key=_sort_key(filters.sort_by))
return flights or None
@@ -515,6 +651,7 @@ class SearchFlights:
currency: str | None,
language: str | None,
country: str | None,
+ tracker: _RowCountTracker | None = None,
) -> list[tuple[FlightResult, ...]] | list[FlightResult]:
"""Fetch next-leg options for round-trip / multi-city in parallel.
@@ -534,6 +671,11 @@ class SearchFlights:
:meth:`get_booking_options` should use; letting expansion workers
race over it would yield non-deterministic results and violate
the "one session per visible search" contract.
+
+ ``tracker``, when given, is forwarded to every worker's
+ :meth:`_fetch_flights` call — it is already lock-guarded (see
+ :class:`_RowCountTracker`), so sharing it across these parallel
+ workers is safe.
"""
num_segments = len(filters.flight_segments)
selected_count = sum(1 for s in filters.flight_segments if s.selected_flight is not None)
@@ -554,6 +696,7 @@ class SearchFlights:
language=language,
country=country,
capture_session=False,
+ tracker=tracker,
)
if sub_flights is None:
return outbound, None
@@ -568,6 +711,7 @@ class SearchFlights:
currency=currency,
language=language,
country=country,
+ tracker=tracker,
)
return outbound, sub_flights
diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py
index 7ed6869..1ea7eb0 100644
--- a/tests/cli/conftest.py
+++ b/tests/cli/conftest.py
@@ -100,6 +100,12 @@ def mock_search_flights(monkeypatch):
mock.build_flight_booking_url.return_value = (
"https://www.google.com/travel/flights/booking?tfs=test"
)
+ # Real SearchFlights.search() sets this False whenever the result isn't
+ # both empty *and* the reason is a page Google itself served empty (see
+ # sparse_passenger_mix on the real class) — default the mock the same
+ # way so tests that don't care about it don't pick up a truthy MagicMock
+ # attribute by accident. Tests that exercise the hint/note set it True.
+ mock.sparse_passenger_mix = False
monkeypatch.setattr("fli.search.flights.SearchFlights.__new__", lambda cls: mock)
monkeypatch.setattr("fli.search.SearchFlights.__new__", lambda cls: mock)
return mock
diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.py
index e272336..336398c 100644
--- a/tests/cli/test_flights.py
+++ b/tests/cli/test_flights.py
@@ -17,6 +17,8 @@ from fli.search.exceptions import (
SearchParseError,
SearchTimeoutError,
)
+from tests.search._pages import as_search_page
+from tests.search.test_parse_flights_data import _leg, _row
@pytest.fixture
@@ -515,6 +517,104 @@ def test_flights_no_results(runner, mock_search_flights, mock_console):
)
assert result.exit_code == 1
assert "No flights found" in result.stdout
+ assert "client-side" not in result.stdout
+
+
+def test_flights_no_results_with_child_explains_the_sparsity(runner, mock_search_flights):
+ """An empty result for a party with children/infants gets the extra hint.
+
+ Google's search page inlines fewer (sometimes zero) rows for those
+ parties — see SPARSE_PASSENGER_MIX_WARNING in fli.search.flights. The
+ CLI reads search_client.sparse_passenger_mix rather than recomputing
+ it, so the mock sets it the way the real library would for this party.
+ """
+ mock_search_flights.search.return_value = []
+ mock_search_flights.sparse_passenger_mix = True
+
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--passengers",
+ "2",
+ "--children",
+ "1",
+ ],
+ )
+ assert result.exit_code == 1
+ assert "No flights found" in result.stdout
+ assert "client-side" in result.stdout
+
+
+def test_flights_no_results_with_infant_explains_the_sparsity(runner, mock_search_flights):
+ mock_search_flights.search.return_value = []
+ mock_search_flights.sparse_passenger_mix = True
+
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--infants-on-lap",
+ "1",
+ ],
+ )
+ assert result.exit_code == 1
+ assert "client-side" in result.stdout
+
+
+class TestFlightsNoteTracksGoogleNotTheCallersFilter:
+ """End-to-end (stubbed page, real ``SearchFlights.search``) — mirrors the MCP-level check.
+
+ A page that genuinely carries no rows still gets the hint; a page that
+ carries a row the caller's own airline filter then removes does not —
+ that emptiness is the filter's doing, not Google's.
+ """
+
+ def _page(self, rows: list) -> str:
+ payload = [[None, None, None, None, "FAKE_SESSION"], None, [rows], None]
+ return as_search_page(payload)
+
+ def _stub_get(self, monkeypatch, body: str) -> None:
+ def _fake_get(self, url, **kwargs): # noqa: ANN001
+ return type("R", (), {"text": body, "raise_for_status": lambda self: None})()
+
+ monkeypatch.setattr("fli.search.client.Client.get", _fake_get)
+
+ def test_genuinely_empty_page_prints_the_hint(self, runner, monkeypatch):
+ self._stub_get(monkeypatch, self._page([]))
+ result = runner.invoke(
+ app,
+ ["flights", "JFK", "LHR", datetime.now().strftime("%Y-%m-%d"), "--children", "1"],
+ )
+ assert result.exit_code == 1
+ assert "No flights found" in result.stdout
+ assert "client-side" in result.stdout
+
+ def test_rows_filtered_out_by_airline_prints_no_hint(self, runner, monkeypatch):
+ row = _row(legs=[_leg(dep_iata="JFK", arr_iata="LHR", airline_code="DL")])
+ self._stub_get(monkeypatch, self._page([row]))
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LHR",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--children",
+ "1",
+ "--airlines",
+ "AA",
+ ],
+ )
+ assert result.exit_code == 1
+ assert "No flights found" in result.stdout
+ assert "client-side" not in result.stdout
def test_basic_round_trip_flights(runner, mock_search_flights, mock_console):
@@ -702,6 +802,37 @@ def test_flights_json_no_results(runner, mock_search_flights, mock_console):
assert payload["success"] is True
assert payload["count"] == 0
assert payload["flights"] == []
+ assert "note" not in payload
+
+
+def test_flights_json_no_results_with_child_carries_a_note(
+ runner, mock_search_flights, mock_console
+):
+ """The JSON empty payload gets the same explanation as a `note` key."""
+ mock_search_flights.search.return_value = []
+ mock_search_flights.sparse_passenger_mix = True
+
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--passengers",
+ "2",
+ "--children",
+ "1",
+ "--format",
+ "json",
+ ],
+ )
+
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ assert payload["success"] is True
+ assert payload["count"] == 0
+ assert "client-side" in payload["note"]
def test_given_comma_separated_origin_list_then_returns_flights_from_all(
diff --git a/tests/mcp/test_mcp_server_unit.py b/tests/mcp/test_mcp_server_unit.py
index 07de36e..a35a035 100644
--- a/tests/mcp/test_mcp_server_unit.py
+++ b/tests/mcp/test_mcp_server_unit.py
@@ -24,6 +24,9 @@ from fli.mcp.server import (
_serialize_flight_leg,
_serialize_layover,
)
+from fli.search.flights import SPARSE_PASSENGER_MIX_WARNING
+from tests.search._pages import as_search_page
+from tests.search.test_parse_flights_data import _leg, _row
# The tool calls below pass fixed travel dates; pin the models' clock so they
# stay in the future no matter when the suite runs.
@@ -634,6 +637,113 @@ class TestSearchReturnsBookingUrl:
assert "booking_url" in result
+class TestEmptyResultSparsePassengerMixNote:
+ """An empty result for children/infants isn't necessarily "no flights".
+
+ Google's search page inlines fewer (sometimes zero) rows for those
+ parties — see ``SPARSE_PASSENGER_MIX_WARNING`` in ``fli.search.flights``.
+ The MCP response carries the same explanation as a ``note`` key so an
+ agent relays it instead of "no flights exist".
+ """
+
+ @pytest.fixture(autouse=True)
+ def _no_flights(self, monkeypatch):
+ # Mirrors SearchFlights.search's real contract (set
+ # sparse_passenger_mix, then return None) rather than a bare
+ # `lambda: None`, so these tests exercise _execute_flight_search
+ # reading search_client.sparse_passenger_mix under the same
+ # condition the real library sets it — a party with a child or
+ # infant — without needing a stubbed HTTP client. The end-to-end
+ # case (the note tracking a genuinely empty Google page rather than
+ # the caller's own filter) is covered separately below with a
+ # stubbed page, where the real search() sets the attribute itself.
+ def _fake_search(self, filters, *a, **k):
+ info = filters.passenger_info
+ self._sparse_passenger_mix = (
+ info.children + info.infants_on_lap + info.infants_in_seat
+ ) > 0
+ return None
+
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _fake_search)
+
+ def test_empty_with_infant_carries_a_note(self):
+ params = FlightSearchParams(
+ origin="JFK", destination="LHR", departure_date="2026-12-01", infants_on_lap=1
+ )
+ result = _execute_flight_search(params)
+ assert result["count"] == 0
+ assert result["note"] == SPARSE_PASSENGER_MIX_WARNING
+
+ def test_empty_with_child_carries_a_note(self):
+ params = FlightSearchParams(
+ origin="JFK", destination="LHR", departure_date="2026-12-01", passengers=2, children=1
+ )
+ result = _execute_flight_search(params)
+ assert result["count"] == 0
+ assert result["note"] == SPARSE_PASSENGER_MIX_WARNING
+
+ def test_empty_adults_only_has_no_note_key(self):
+ params = FlightSearchParams(origin="JFK", destination="LHR", departure_date="2026-12-01")
+ result = _execute_flight_search(params)
+ assert result["count"] == 0
+ assert "note" not in result
+
+ def test_non_empty_with_infant_has_no_note_key(self, monkeypatch):
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ params = FlightSearchParams(
+ origin="JFK", destination="LHR", departure_date="2026-12-01", infants_in_seat=1
+ )
+ result = _execute_flight_search(params)
+ assert result["count"] == 1
+ assert "note" not in result
+
+
+class TestEmptyResultNoteTracksGoogleNotTheCallersFilter:
+ """End-to-end (stubbed page, real ``SearchFlights.search``).
+
+ A page that genuinely carries no rows still gets the note; a page that
+ carries a row the caller's own airline filter then removes does not —
+ that emptiness is the filter's doing, not Google's.
+ """
+
+ def _page(self, rows: list) -> str:
+ payload = [[None, None, None, None, "FAKE_SESSION"], None, [rows], None]
+ return as_search_page(payload)
+
+ def _stub_get(self, monkeypatch, body: str) -> None:
+ def _fake_get(self, url, **kwargs): # noqa: ANN001
+ return type("R", (), {"text": body, "raise_for_status": lambda self: None})()
+
+ monkeypatch.setattr("fli.search.client.Client.get", _fake_get)
+
+ def test_genuinely_empty_page_carries_a_note(self, monkeypatch):
+ self._stub_get(monkeypatch, self._page([]))
+ params = FlightSearchParams(
+ origin="JFK", destination="LHR", departure_date="2026-12-01", children=1
+ )
+ result = _execute_flight_search(params)
+ assert result["count"] == 0
+ assert result["note"] == SPARSE_PASSENGER_MIX_WARNING
+
+ def test_rows_filtered_out_by_airline_has_no_note_key(self, monkeypatch):
+ row = _row(legs=[_leg(dep_iata="JFK", arr_iata="LHR", airline_code="DL")])
+ self._stub_get(monkeypatch, self._page([row]))
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date="2026-12-01",
+ children=1,
+ airlines=["AA"],
+ )
+ result = _execute_flight_search(params)
+ assert result["count"] == 0
+ assert "note" not in result
+
+
class TestExecuteBookingOptions:
@pytest.fixture
def params(self):
diff --git a/tests/search/test_sparse_passenger_warning.py b/tests/search/test_sparse_passenger_warning.py
new file mode 100644
index 0000000..5fa447a
--- /dev/null
+++ b/tests/search/test_sparse_passenger_warning.py
@@ -0,0 +1,632 @@
+"""Offline tests for the sparse-passenger-mix warning on empty results.
+
+Google's search-page transport inlines fewer (sometimes zero) rows for
+parties with children or infants — the fares are priced client-side through
+the gated RPC this transport cannot reach. An empty ``SearchFlights.search``
+or ``SearchDates.search`` result for such a party used to be indistinguishable
+from a route with no service at all; these tests pin the one warning each
+call logs to explain the difference, and confirm it stays silent whenever it
+would not apply.
+
+A result can also come back empty because the *caller's own* client-side
+filter (airline, price cap, max duration, departure window) removed every
+row Google did inline — that is not evidence of the passenger-mix pricing
+gap, so a second family of tests below pins that the warning (and the
+``sparse_passenger_mix`` attribute both classes expose) only fires when at
+least one fetched page decoded to zero rows *before* filtering.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+from datetime import datetime, timedelta
+
+import pytest
+
+from fli.models import (
+ Airline,
+ Airport,
+ DateSearchFilters,
+ FlightSearchFilters,
+ FlightSegment,
+ PassengerInfo,
+)
+from fli.models.google_flights.base import TripType
+from fli.search import dates as dates_module
+from fli.search.exceptions import SearchParseError
+from fli.search.flights import SPARSE_PASSENGER_MIX_WARNING, SearchFlights
+from tests.search._pages import as_search_page
+from tests.search.test_parse_flights_data import _leg, _row
+
+
+def _future(days: int) -> str:
+ return (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")
+
+
+def _one_way_filters(passenger_info: PassengerInfo, **overrides) -> FlightSearchFilters:
+ return FlightSearchFilters(
+ passenger_info=passenger_info,
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date=_future(45),
+ )
+ ],
+ **overrides,
+ )
+
+
+def _round_trip_filters(passenger_info: PassengerInfo, **overrides) -> FlightSearchFilters:
+ return FlightSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=passenger_info,
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date=_future(45),
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.LAX, 0]],
+ arrival_airport=[[Airport.JFK, 0]],
+ travel_date=_future(52),
+ ),
+ ],
+ **overrides,
+ )
+
+
+def _page(rows: list) -> str:
+ payload = [
+ [None, None, None, None, "FAKE_SESSION"],
+ None,
+ [rows],
+ None,
+ ]
+ return as_search_page(payload)
+
+
+def _row_page(airline_code: str = "DL") -> str:
+ """Build a search page carrying exactly one parseable flight row."""
+ return _page([_row(legs=[_leg(dep_iata="JFK", arr_iata="LAX", airline_code=airline_code)])])
+
+
+def _empty_page() -> str:
+ """Build a search page whose ``ds:1`` payload holds no rows."""
+ return _page([])
+
+
+def _client_serving(monkeypatch, bodies: list[str]) -> SearchFlights:
+ """Return a ``SearchFlights`` whose ``client.get`` serves ``bodies`` in call order."""
+ sf = SearchFlights()
+ calls: list[str] = []
+
+ def _fake_get(url, **kwargs): # noqa: ANN001
+ body = bodies[min(len(calls), len(bodies) - 1)]
+ calls.append(url)
+ return type("R", (), {"text": body, "raise_for_status": lambda self: None})()
+
+ monkeypatch.setattr(sf.client, "get", _fake_get)
+ return sf
+
+
+def _warnings(caplog):
+ return [r for r in caplog.records if r.levelno == logging.WARNING]
+
+
+class TestSparsePassengerMixWarningOneWay:
+ def test_empty_with_child_warns_exactly_once(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _one_way_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ warnings = _warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert warnings[0].getMessage() == SPARSE_PASSENGER_MIX_WARNING
+ assert sf.sparse_passenger_mix is True
+
+ def test_empty_with_lap_infant_warns_exactly_once(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _one_way_filters(PassengerInfo(adults=1, infants_on_lap=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ warnings = _warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert warnings[0].getMessage() == SPARSE_PASSENGER_MIX_WARNING
+
+ def test_empty_with_seat_infant_warns_exactly_once(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _one_way_filters(PassengerInfo(adults=1, infants_in_seat=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ warnings = _warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+
+ def test_empty_adults_only_does_not_warn(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _one_way_filters(PassengerInfo(adults=2))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ assert _warnings(caplog) == []
+ assert sf.sparse_passenger_mix is False
+
+ def test_rows_with_child_does_not_warn(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_row_page()])
+ filters = _one_way_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is not None
+ assert _warnings(caplog) == []
+ assert sf.sparse_passenger_mix is False
+
+
+class TestSparsePassengerMixWarningRoundTrip:
+ def test_empty_outbound_with_child_warns_exactly_once(self, monkeypatch, caplog):
+ """The outbound page itself carries no rows — search stops right there."""
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _round_trip_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ warnings = _warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert warnings[0].getMessage() == SPARSE_PASSENGER_MIX_WARNING
+ assert sf.sparse_passenger_mix is True
+
+ def test_empty_return_leg_with_child_warns_exactly_once(self, monkeypatch, caplog):
+ """Outbound has rows but every expansion fetch for the return comes back empty.
+
+ ``_fetch_flights`` runs twice here (outbound + one expansion candidate);
+ the warning must still fire only once for the whole ``search()`` call.
+ """
+ sf = _client_serving(monkeypatch, [_row_page(), _empty_page()])
+ filters = _round_trip_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert not result
+ warnings = _warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert warnings[0].getMessage() == SPARSE_PASSENGER_MIX_WARNING
+ assert sf.sparse_passenger_mix is True
+
+ def test_empty_round_trip_adults_only_does_not_warn(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_row_page(), _empty_page()])
+ filters = _round_trip_filters(PassengerInfo(adults=2))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert not result
+ assert _warnings(caplog) == []
+
+ def test_rows_on_both_legs_with_child_does_not_warn(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_row_page(), _row_page()])
+ filters = _round_trip_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result
+ assert _warnings(caplog) == []
+
+
+class TestSparsePassengerMixMisattribution:
+ """The warning must blame Google's page, not the caller's own filter.
+
+ Every row here is on airline DL; filtering for AA removes it entirely —
+ Google *did* inline something, so the sparse-mix diagnosis does not
+ apply even though the final result is empty and the party has a child.
+ """
+
+ def test_one_way_rows_filtered_out_by_airline_does_not_warn(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_row_page(airline_code="DL")])
+ filters = _one_way_filters(PassengerInfo(adults=1, children=1), airlines=[Airline.AA])
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ assert _warnings(caplog) == []
+ assert sf.sparse_passenger_mix is False
+
+ def test_round_trip_outbound_rows_filtered_out_does_not_warn(self, monkeypatch, caplog):
+ """Outbound page has a row (Google inlined it); the airline filter removes it.
+
+ Never even reaches the return-leg fetch, since the outbound leg's
+ post-filter result is already empty.
+ """
+ sf = _client_serving(monkeypatch, [_row_page(airline_code="DL")])
+ filters = _round_trip_filters(PassengerInfo(adults=1, children=1), airlines=[Airline.AA])
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert result is None
+ assert _warnings(caplog) == []
+ assert sf.sparse_passenger_mix is False
+
+ def test_round_trip_outbound_survives_return_leg_filtered_out_does_not_warn(
+ self, monkeypatch, caplog
+ ):
+ """Outbound row matches the filter; the return-leg row does not.
+
+ The return-leg page still carried a row (Google inlined it) — the
+ caller's own filter removed it, not Google. Distinguishes this from
+ ``test_empty_return_leg_with_child_warns_exactly_once``, where the
+ return-leg *page itself* has zero rows.
+ """
+ sf = _client_serving(
+ monkeypatch, [_row_page(airline_code="AA"), _row_page(airline_code="DL")]
+ )
+ filters = _round_trip_filters(PassengerInfo(adults=1, children=1), airlines=[Airline.AA])
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ result = sf.search(filters)
+ assert not result
+ assert _warnings(caplog) == []
+ assert sf.sparse_passenger_mix is False
+
+
+class TestSparsePassengerMixAttributeLifecycle:
+ def test_resets_to_false_after_a_non_sparse_search_on_the_same_instance(
+ self, monkeypatch, caplog
+ ):
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _one_way_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ sf.search(filters)
+ assert sf.sparse_passenger_mix is True
+
+ monkeypatch.setattr(
+ sf.client,
+ "get",
+ lambda url, **kwargs: type(
+ "R", (), {"text": _row_page(), "raise_for_status": lambda self: None}
+ )(),
+ )
+ result = sf.search(_one_way_filters(PassengerInfo(adults=1, children=1)))
+ assert result is not None
+ assert sf.sparse_passenger_mix is False
+
+ def test_resets_to_false_before_a_search_that_raises(self, monkeypatch, caplog):
+ sf = _client_serving(monkeypatch, [_empty_page()])
+ filters = _one_way_filters(PassengerInfo(adults=1, children=1))
+ with caplog.at_level(logging.WARNING, logger="fli.search.flights"):
+ sf.search(filters)
+ assert sf.sparse_passenger_mix is True
+
+ blank = "<html>no data callback here</html>"
+ monkeypatch.setattr(
+ sf.client,
+ "get",
+ lambda url, **kwargs: type(
+ "R", (), {"text": blank, "raise_for_status": lambda self: None}
+ )(),
+ )
+ with pytest.raises(SearchParseError):
+ sf.search(_one_way_filters(PassengerInfo(adults=1, children=1)))
+ assert sf.sparse_passenger_mix is False
+
+
+ "info",
+ [
+ PassengerInfo(adults=1),
+ PassengerInfo(adults=5),
+ ],
+)
+def test_has_children_or_infants_false_for_adults_only(info):
+ from fli.search.flights import _has_children_or_infants
+
+ assert _has_children_or_infants(info) is False
+
+
+ "info",
+ [
+ PassengerInfo(adults=1, children=1),
+ PassengerInfo(adults=1, infants_on_lap=1),
+ PassengerInfo(adults=1, infants_in_seat=1),
+ ],
+)
+def test_has_children_or_infants_true(info):
+ from fli.search.flights import _has_children_or_infants
+
+ assert _has_children_or_infants(info) is True
+
+
+class TestSparseWarningRaceLoop:
+ """Confirm the exactly-once guarantee under real thread-pool concurrency.
+
+ Round-trip: 3 outbound rows spin up 3 parallel expansion workers, every
+ return-leg fetch is empty. 200 iterations, checking the warning fires
+ exactly once every time and never zero or twice.
+ """
+
+ def _three_row_page(self) -> str:
+ rows = [
+ _row(
+ legs=[_leg(dep_iata="JFK", arr_iata="LAX")],
+ price=100 + i,
+ booking_token=f"TOK{i}",
+ )
+ for i in range(3)
+ ]
+ return _page(rows)
+
+ def _one_run(self) -> tuple[int, object]:
+ sf = SearchFlights()
+ calls: list[int] = []
+ lock = threading.Lock()
+
+ def _fake_get(url, **kwargs): # noqa: ANN001
+ with lock:
+ n = len(calls)
+ calls.append(n)
+ body = self._three_row_page() if n == 0 else _empty_page()
+ return type("R", (), {"text": body, "raise_for_status": lambda self: None})()
+
+ sf.client.get = _fake_get
+ filters = _round_trip_filters(PassengerInfo(adults=1, children=1))
+
+ logger = logging.getLogger("fli.search.flights")
+ records: list[logging.LogRecord] = []
+
+ class _Handler(logging.Handler):
+ def emit(self, record: logging.LogRecord) -> None:
+ records.append(record)
+
+ handler = _Handler()
+ logger.addHandler(handler)
+ logger.setLevel(logging.WARNING)
+ try:
+ result = sf.search(filters, top_n=5)
+ finally:
+ logger.removeHandler(handler)
+
+ sparse = [r for r in records if r.getMessage() == SPARSE_PASSENGER_MIX_WARNING]
+ return len(sparse), result
+
+ def test_two_hundred_iterations_always_warn_exactly_once(self):
+ counts: dict[int, int] = {}
+ bad_runs = []
+ for i in range(200):
+ n, result = self._one_run()
+ counts[n] = counts.get(n, 0) + 1
+ if n != 1 or result:
+ bad_runs.append((i, n, result))
+ assert not bad_runs, f"warning-count distribution: {counts}; bad runs: {bad_runs[:5]}"
+ assert counts == {1: 200}
+
+
+# ---------------------------------------------------------------------------
+# fli.search.dates.SearchDates
+# ---------------------------------------------------------------------------
+
+FIRST_DAY = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=30)
+
+
+def _date_filters(days: int, passenger_info: PassengerInfo, **overrides) -> DateSearchFilters:
+ """One-way date filters spanning ``days`` dates starting at FIRST_DAY."""
+ return DateSearchFilters(
+ trip_type=TripType.ONE_WAY,
+ passenger_info=passenger_info,
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date=FIRST_DAY.strftime("%Y-%m-%d"),
+ )
+ ],
+ from_date=FIRST_DAY.strftime("%Y-%m-%d"),
+ to_date=(FIRST_DAY + timedelta(days=days - 1)).strftime("%Y-%m-%d"),
+ **overrides,
+ )
+
+
+class _DateResponse:
+ def __init__(self, text: str) -> None:
+ self.text = text
+
+ def raise_for_status(self) -> None:
+ return None
+
+
+class _CountingDateClient:
+ """Serves ``body`` for every date request; thread-safe call counter."""
+
+ def __init__(self, body: str) -> None:
+ self.body = body
+ self.calls = 0
+ self._lock = threading.Lock()
+
+ def get(self, url: str, **kwargs): # noqa: ANN001
+ with self._lock:
+ self.calls += 1
+ return _DateResponse(self.body)
+
+
+def _search_dates_with(client) -> dates_module.SearchDates:
+ search = dates_module.SearchDates()
+ search.client = client
+ return search
+
+
+def _date_warnings(caplog):
+ return [r for r in caplog.records if r.levelno == logging.WARNING]
+
+
+class TestSparsePassengerMixWarningDatesUnit:
+ """Drives ``SearchDates._warn_if_sparse_passenger_mix`` directly.
+
+ Mirrors how ``TestSweepCircuitBreaker`` in ``test_date_sweep.py`` drives
+ ``_collect`` directly: the interesting states are a property of a fixed
+ set of outcomes, not of racing a real sweep's concurrent fetches.
+ """
+
+ def test_no_result_no_failures_with_child_warns_once(self, caplog):
+ outcomes = [dates_module._DateOutcome(rows_before_filters=0) for _ in range(3)]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ warned = dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, None, PassengerInfo(adults=1, children=1)
+ )
+ warnings = _date_warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert warnings[0].getMessage() == dates_module.SPARSE_PASSENGER_MIX_WARNING
+ assert warned is True
+
+ def test_no_result_no_failures_adults_only_does_not_warn(self, caplog):
+ outcomes = [dates_module._DateOutcome(rows_before_filters=0) for _ in range(3)]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ warned = dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, None, PassengerInfo(adults=2)
+ )
+ assert _date_warnings(caplog) == []
+ assert warned is False
+
+ def test_no_result_with_a_failure_and_child_does_not_warn(self, caplog):
+ """A failed date means ``_collect`` already explains the gap — see its docstring."""
+ outcomes = [
+ dates_module._DateOutcome(rows_before_filters=0),
+ dates_module._DateOutcome(rows_before_filters=0),
+ dates_module._DateOutcome(rows_before_filters=0),
+ dates_module._DateOutcome(failure="SearchConnectionError: transient"),
+ ]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ warned = dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, None, PassengerInfo(adults=1, children=1)
+ )
+ assert _date_warnings(caplog) == []
+ assert warned is False
+
+ def test_a_result_with_child_does_not_warn(self, caplog):
+ priced = dates_module.DatePrice(date=(FIRST_DAY,), price=150.0, currency="USD")
+ outcomes = [dates_module._DateOutcome(price=priced, rows_before_filters=1)]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ warned = dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, [priced], PassengerInfo(adults=1, children=1)
+ )
+ assert _date_warnings(caplog) == []
+ assert warned is False
+
+ def test_no_result_rows_filtered_out_every_date_does_not_warn(self, caplog):
+ """Every date's page carried rows; the caller's own filter emptied all of them."""
+ outcomes = [dates_module._DateOutcome(rows_before_filters=2) for _ in range(3)]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ warned = dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, None, PassengerInfo(adults=1, children=1)
+ )
+ assert _date_warnings(caplog) == []
+ assert warned is False
+
+ def test_no_result_mixed_zero_and_filtered_rows_still_warns(self, caplog):
+ """At least one date's page was genuinely empty — still the pricing gap."""
+ outcomes = [
+ dates_module._DateOutcome(rows_before_filters=2),
+ dates_module._DateOutcome(rows_before_filters=0),
+ ]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ warned = dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, None, PassengerInfo(adults=1, children=1)
+ )
+ assert len(_date_warnings(caplog)) == 1
+ assert warned is True
+
+ def test_one_failed_plus_three_empty_with_child_warns_exactly_once_total(self, caplog):
+ """1 failed + 3 empty + child: exactly ONE warning overall, and it is #249's.
+
+ Exercises ``_collect`` and ``_warn_if_sparse_passenger_mix`` together,
+ in the same order ``SearchDates.search`` calls them, so the "cannot
+ stack" contract between the two is pinned directly rather than only
+ inferred from a full network sweep (which would also carry
+ ``_price_one_date``'s own per-date failure warning and muddy the count).
+ """
+ outcomes = [
+ dates_module._DateOutcome(rows_before_filters=0),
+ dates_module._DateOutcome(rows_before_filters=0),
+ dates_module._DateOutcome(rows_before_filters=0),
+ dates_module._DateOutcome(failure="SearchConnectionError: transient"),
+ ]
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ result = dates_module.SearchDates._collect(outcomes, 4, skipped=0)
+ dates_module.SearchDates._warn_if_sparse_passenger_mix(
+ outcomes, result, PassengerInfo(adults=1, children=1)
+ )
+ assert result is None
+ warnings = _date_warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ # The one warning must be #249's minority-failure summary, not ours.
+ assert warnings[0].getMessage() != dates_module.SPARSE_PASSENGER_MIX_WARNING
+ assert "loaded" in warnings[0].getMessage()
+
+
+class TestSparsePassengerMixWarningDatesIntegration:
+ """End-to-end through ``SearchDates.search`` with a stubbed HTTP client."""
+
+ def test_empty_sweep_with_child_warns_exactly_once(self, caplog):
+ client = _CountingDateClient(_empty_page())
+ filters = _date_filters(3, PassengerInfo(adults=1, children=1))
+ search = _search_dates_with(client)
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ result = search.search(filters)
+ assert result is None
+ warnings = _date_warnings(caplog)
+ assert len(warnings) == 1, f"expected exactly one warning, got {len(warnings)}"
+ assert warnings[0].getMessage() == dates_module.SPARSE_PASSENGER_MIX_WARNING
+ assert search.sparse_passenger_mix is True
+
+ def test_empty_sweep_adults_only_does_not_warn(self, caplog):
+ client = _CountingDateClient(_empty_page())
+ filters = _date_filters(3, PassengerInfo(adults=2))
+ search = _search_dates_with(client)
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ result = search.search(filters)
+ assert result is None
+ assert _date_warnings(caplog) == []
+ assert search.sparse_passenger_mix is False
+
+ def test_sweep_with_results_and_child_does_not_warn(self, caplog):
+ client = _CountingDateClient(_row_page())
+ filters = _date_filters(3, PassengerInfo(adults=1, children=1))
+ search = _search_dates_with(client)
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ result = search.search(filters)
+ assert result is not None
+ assert _date_warnings(caplog) == []
+ assert search.sparse_passenger_mix is False
+
+ def test_sweep_rows_filtered_out_by_airline_every_date_does_not_warn(self, caplog):
+ """Every date's page carried a DL row; an AA-only filter empties every date."""
+ client = _CountingDateClient(_row_page(airline_code="DL"))
+ filters = _date_filters(3, PassengerInfo(adults=1, children=1), airlines=[Airline.AA])
+ search = _search_dates_with(client)
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ result = search.search(filters)
+ assert result is None
+ assert _date_warnings(caplog) == []
+ assert search.sparse_passenger_mix is False
+
+ def test_attribute_resets_after_a_non_sparse_sweep_on_the_same_instance(self, caplog):
+ client = _CountingDateClient(_empty_page())
+ search = _search_dates_with(client)
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ search.search(_date_filters(3, PassengerInfo(adults=1, children=1)))
+ assert search.sparse_passenger_mix is True
+
+ search.client = _CountingDateClient(_row_page())
+ result = search.search(_date_filters(3, PassengerInfo(adults=1, children=1)))
+ assert result is not None
+ assert search.sparse_passenger_mix is False
+
+ def test_attribute_resets_before_a_sweep_that_raises(self, caplog):
+ """A sweep that raises must not leave the previous sweep's verdict behind."""
+ client = _CountingDateClient(_empty_page())
+ search = _search_dates_with(client)
+ with caplog.at_level(logging.WARNING, logger="fli.search.dates"):
+ search.search(_date_filters(3, PassengerInfo(adults=1, children=1)))
+ assert search.sparse_passenger_mix is True
+
+ # Over the per-search date cap: raises before any page is fetched.
+ too_many = dates_module.MAX_DATES_PER_SEARCH + 1
+ calls_before = client.calls
+ with pytest.raises(ValueError, match="date limit"):
+ search.search(_date_filters(too_many, PassengerInfo(adults=1, children=1)))
+ assert client.calls == calls_before
+ assert search.sparse_passenger_mix is False