Google Flights MCP, CLI and Python Library
fix: decode per-leg amenity slots correctly (Wi-Fi, power, video, seat quality, cabin) (#244)
Punit Arani0caa8b2fe404
diff --git a/fli-js/src/models/google-flights/base.ts b/fli-js/src/models/google-flights/base.tsindex d7681c4..13bc214 100644--- a/fli-js/src/models/google-flights/base.ts+++ b/fli-js/src/models/google-flights/base.ts@@ -173,6 +173,50 @@ export const LayoverRestrictionsSchema = z.object({});export type LayoverRestrictions = z.infer<typeof LayoverRestrictionsSchema>;+/** In-seat power flavour decoded from the leg[12] power slot group. */+export const POWER_TYPES = ["plug_and_usb", "plug", "usb"] as const;+export type PowerType = (typeof POWER_TYPES)[number];++/** In-flight entertainment flavour decoded from the leg[12] video group. */+export const VIDEO_TYPES = ["live_tv", "on_demand", "stream_to_device"] as const;+export type VideoType = (typeof VIDEO_TYPES)[number];++/** Whether Google flags the leg's Wi-Fi as complimentary or chargeable. */+export const WIFI_TIERS = ["free", "paid"] as const;+export type WifiTier = (typeof WIFI_TIERS)[number];++/**+ * Human-readable label for Google's leg[13] seat-quality code.+ *+ * These are labels, not an ordered score: "average"/"below_average"/+ * "above_average" describe an economy-style pitch, while the remaining four+ * name a seat *product*. The code tracks the fare's cabin rather than the+ * airframe — in the captured fixtures AA 1209 (ORD-LAX, 737 MAX 8) appears+ * twice, as "average" in economy and "recliner" in first.+ */+export const SEAT_QUALITIES = [+ "average",+ "below_average",+ "above_average",+ "extra_reclining",+ "lie_flat",+ "lie_flat_suite_with_door",+ "recliner",+] as const;+export type SeatQuality = (typeof SEAT_QUALITIES)[number];++/**+ * Per-leg amenities reported by Google Flights. Booleans are tri-state+ * (true / false / null when Google did not publish that signal).+ *+ * Google never publishes an explicit "no" for any of these amenities — the+ * wire format only ever sets a flag or omits it — so `false` is always an+ * inference and is used exactly once: `in_seat_video` is false when+ * `video_type === "stream_to_device"`, which is Google's way of saying the+ * aircraft has no seatback screen. Every other unknown stays null,+ * including `usb_power` for a plug-only cabin and `on_demand_video` for a+ * live-TV or stream-to-device leg.+ */export const AmenitiesSchema = z.object({wifi: z.boolean().nullable().optional(),power: z.boolean().nullable().optional(),@@ -180,6 +224,13 @@ export const AmenitiesSchema = z.object({in_seat_video: z.boolean().nullable().optional(),on_demand_video: z.boolean().nullable().optional(),legroom_rating: z.number().int().nonnegative().nullable().optional(),+ // Optional detail — populated only for slot values confirmed against+ // captured responses, so callers never see a confidently wrong label.+ wifi_tier: z.enum(WIFI_TIERS).nullable().optional(),+ power_type: z.enum(POWER_TYPES).nullable().optional(),+ video_type: z.enum(VIDEO_TYPES).nullable().optional(),+ seat_quality: z.enum(SEAT_QUALITIES).nullable().optional(),+ legroom_inches: z.number().int().positive().nullable().optional(),});export type Amenities = z.infer<typeof AmenitiesSchema>;@@ -210,6 +261,11 @@ export interface FlightLeg {amenities?: Amenities | null;overnight?: boolean;co2_emissions_g?: number | null;+ /**+ * Cabin actually flown on this leg, from leg[16]. Per-leg, so a business+ * itinerary can still show an economy connecting leg.+ */+ cabin?: SeatType | null;}export interface BookingOption {diff --git a/fli-js/src/search/decoders.ts b/fli-js/src/search/decoders.tsindex fac86a8..88b1d01 100644--- a/fli-js/src/search/decoders.ts+++ b/fli-js/src/search/decoders.ts@@ -12,7 +12,12 @@ import type {FlightLeg,FlightResult,Layover,+ PowerType,+ SeatQuality,+ VideoType,+ WifiTier,} from "../models/google-flights/base.ts";+import { SeatType } from "../models/google-flights/base.ts";import { asBool, asInt, asNonNegativeInt, asStr, safeGet } from "./helpers.ts";// Pseudo-codes Google emits in place of a real IATA carrier identifier.@@ -71,25 +76,171 @@ function safeAirline(code: unknown): Airline | null {return null;}-function parseAmenities(slots: unknown, seatQuality: unknown = null): Amenities | null {- const wifi = asBool(safeGet(slots, 1));- const power = asBool(safeGet(slots, 5));- const onDemandVideo = asBool(safeGet(slots, 9));+// --- leg[12] amenity slot map (issue #217) --------------------------------+//+// leg[12] is a sparse array of amenity flags with trailing nulls trimmed.+// Two mutually-exclusive groups plus a Wi-Fi tier code were confirmed by+// tabulating all 481 leg instances across the captured fixtures (plus+// three live public-page captures) against published fleet facts:+//+// slots 1..6 power group — exactly one is ever set on a leg.+// slots 8..10 video group — exactly one is ever set on a leg.+// slot 11 Wi-Fi tier code (a number, never a bool).+//+// Slots 2, 4 and 6 are reported to be "some seats only" variants of 1, 3+// and 5, and slot 11 === 1 is reported to mean "Wi-Fi, tier unknown", but+// none of those values occurs anywhere in the corpus. Nothing is inferred+// from them: an unobserved slot yields null, never a guessed value.+//+// No slot in the corpus ever holds JSON `false`, so every `false` this+// decoder emits is an inference. Only one is made — see `inSeatVideo` in+// parseAmenities.++/** Power slots whose flavour is confirmed. */+const POWER_SLOTS: ReadonlyMap<number, PowerType> = new Map<number, PowerType>([+ [1, "plug_and_usb"],+ [3, "plug"],+ [5, "usb"],+]);+/**+ * Every index in the power group, scanned in wire order. Includes the+ * unobserved 2/4/6 "some seats" variants deliberately: the first *set* slot+ * wins even when it is one we cannot label, so a payload that ever does set+ * one yields "unknown" rather than skipping ahead to a slot we can name and+ * reporting something Google did not say.+ */+const POWER_GROUP: readonly number[] = [1, 2, 3, 4, 5, 6];+/** Video slots, in wire order. */+const VIDEO_SLOTS: ReadonlyMap<number, VideoType> = new Map<number, VideoType>([+ [8, "live_tv"],+ [9, "on_demand"],+ [10, "stream_to_device"],+]);+const VIDEO_GROUP: readonly number[] = [8, 9, 10];+/** Video products delivered on a seatback screen rather than to a phone. */+const SEATBACK_VIDEO: ReadonlySet<VideoType> = new Set<VideoType>(["live_tv", "on_demand"]);+/** Position of the Wi-Fi tier code within leg[12]. */+const WIFI_TIER_SLOT = 11;+/** Confirmed Wi-Fi tier codes. */+const WIFI_TIERS_BY_CODE: ReadonlyMap<number, WifiTier> = new Map<number, WifiTier>([+ [2, "free"],+ [3, "paid"],+]);+/**+ * Confirmed leg[13] seat-quality codes. Code 9 ("angled flat") is reported+ * but unobserved, so it deliberately has no label here.+ */+const SEAT_QUALITY_BY_CODE: ReadonlyMap<number, SeatQuality> = new Map<number, SeatQuality>([+ [1, "average"],+ [2, "below_average"],+ [3, "above_average"],+ [4, "extra_reclining"],+ [5, "lie_flat"],+ [6, "lie_flat_suite_with_door"],+ [8, "recliner"],+]);++/**+ * True when slots[index] is a set flag. Google's RPC payload encodes these+ * as JSON booleans while the public travel page encodes them as 1; accept+ * both and treat every other value (including 0, non-integers and strings)+ * as unset. The integer check keeps this identical to Python's+ * `isinstance(value, int)`, which rejects floats such as 1.5.+ */+function slotOn(slots: unknown, index: number): boolean {+ const value = safeGet(slots, index);+ if (typeof value === "boolean") return value;+ return typeof value === "number" && Number.isInteger(value) && value > 0;+}++/** Index of the first set slot in `group` (wire order), else null. */+function firstSetSlot(slots: unknown, group: readonly number[]): number | null {+ for (const index of group) {+ if (slotOn(slots, index)) return index;+ }+ return null;+}++/** Pull the integer seat pitch out of "31 in" / "31 inches". */+function parseLegroomInches(text: unknown): number | null {+ if (typeof text !== "string") return null;+ const head = text.split(" ", 1)[0];+ if (head == null || !/^\d+$/.test(head)) return null;+ const inches = Number.parseInt(head, 10);+ return inches > 0 ? inches : null;+}++function parseAmenities(+ slots: unknown,+ seatQuality: unknown = null,+ legroom: unknown = null,+): Amenities | null {+ // Only a slot whose meaning the corpus confirms may set `power`; an+ // unlabelled slot (2/4/6, never observed) leaves every power field+ // unknown rather than asserting "there is power, flavour unknown".+ const powerSlot = firstSetSlot(slots, POWER_GROUP);+ const powerType = powerSlot == null ? null : (POWER_SLOTS.get(powerSlot) ?? null);+ const power = powerType == null ? null : true;+ // `powerType === "plug"` is the AC-outlet-only variant, but it rests on 7+ // legs from 2 carriers in the whole corpus — far too thin to put a false+ // on a public tri-state. The distinction survives losslessly in+ // `power_type`; `usb_power` only ever says true or "unknown".+ const usbPower = powerType === "plug_and_usb" || powerType === "usb" ? true : null;++ const videoSlot = firstSetSlot(slots, VIDEO_GROUP);+ const videoType = videoSlot == null ? null : (VIDEO_SLOTS.get(videoSlot) ?? null);+ // INFERENCE: "stream to your own device" is Google's way of saying the+ // aircraft has no seatback screen — true of every slot-10 fleet in the+ // corpus (Alaska, AA 737/A321 Sharklets, every regional jet) — so it is+ // the one negative these slots license. Nothing else is inferred: a+ // live-TV seatback normally carries on-demand content too, and streamed+ // content is itself on-demand, so the absence of slot 9 is not evidence+ // that on-demand is unavailable.+ const inSeatVideo = videoType == null ? null : SEATBACK_VIDEO.has(videoType);+ const onDemandVideo = videoType === "on_demand" ? true : null;++ const wifiCode = asNonNegativeInt(safeGet(slots, WIFI_TIER_SLOT));+ const wifi = wifiCode ? true : null;+ const wifiTier = wifiCode ? (WIFI_TIERS_BY_CODE.get(wifiCode) ?? null) : null;+// leg[12][11] is the Wi-Fi tier; seat quality lives separately at leg[13].const legroomRating = asNonNegativeInt(seatQuality);- if (wifi == null && power == null && onDemandVideo == null && legroomRating == null) {+ const seatQualityLabel =+ legroomRating == null ? null : (SEAT_QUALITY_BY_CODE.get(legroomRating) ?? null);++ // legroom_inches is derived from a string the leg already exposes as+ // legroom/legroom_short, so on its own it is not enough to materialise an+ // Amenities object — that keeps "no amenities" meaning what it did before+ // this decoder was corrected.+ if (wifi == null && power == null && videoType == null && legroomRating == null) {return null;}return {- wifi: wifi ?? null,- power: power ?? null,- usb_power: null,- in_seat_video: null,- on_demand_video: onDemandVideo ?? null,+ wifi,+ power,+ usb_power: usbPower,+ in_seat_video: inSeatVideo,+ on_demand_video: onDemandVideo,legroom_rating: legroomRating ?? null,+ wifi_tier: wifiTier,+ power_type: powerType,+ video_type: videoType,+ seat_quality: seatQualityLabel,+ legroom_inches: parseLegroomInches(legroom),};}+/**+ * Decode the per-leg cabin code at leg[16] into a SeatType. Google uses the+ * same 1..4 numbering here as in the request filters. Unknown codes return+ * null rather than throwing — the leg is still usable.+ */+function parseCabin(code: unknown): SeatType | null {+ const value = asNonNegativeInt(code);+ if (value == null) return null;+ return (Object.values(SeatType) as number[]).includes(value) ? (value as SeatType) : null;+}+interface EmissionsBlock {this_g: number | null;typical_g: number | null;@@ -121,12 +272,13 @@ function parseLeg(fl: unknown[]): FlightLeg {const opCode = safeGet(airlineInfo, 2);const operatingAirline = opCode ? safeAirline(opCode) : null;- const amenities = parseAmenities(safeGet(fl, 12), safeGet(fl, 13));const aircraft = asStr(safeGet(fl, 17));const legroomShort = asStr(safeGet(fl, 14));const legroomLong = asStr(safeGet(fl, 30));+ const amenities = parseAmenities(safeGet(fl, 12), safeGet(fl, 13), legroomShort ?? legroomLong);const overnight = asBool(safeGet(fl, 19)) ?? false;const co2EmissionsG = asNonNegativeInt(safeGet(fl, 31));+ const cabin = parseCabin(safeGet(fl, 16));return {airline,@@ -146,6 +298,7 @@ function parseLeg(fl: unknown[]): FlightLeg {amenities,overnight,co2_emissions_g: co2EmissionsG,+ cabin,};}diff --git a/fli-js/tests/search/amenities_decoding.test.ts b/fli-js/tests/search/amenities_decoding.test.tsnew file mode 100644index 0000000..1c843fd--- /dev/null+++ b/fli-js/tests/search/amenities_decoding.test.ts@@ -0,0 +1,435 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import type { FlightLeg, FlightResult } from "../../src/models/google-flights/base.ts";+import { SeatType } from "../../src/models/google-flights/base.ts";+import { parseFlightRow } from "../../src/search/decoders.ts";++/**+ * Mirror of tests/search/test_amenities_decoding.py (issue #217).+ *+ * Every expectation is pinned to a named flight in a captured Google+ * Flights response. The slot mapping was verified by tabulating+ * leg[12][0..11], leg[13], leg[14] and leg[16] across ~280 distinct legs:+ * slots 1..6 are a mutually-exclusive power group, slots 8..10 a+ * mutually-exclusive video group, and slot 11 a Wi-Fi tier code.+ */++function load(name: string): FlightResult[] {+ const fixture = readFileSync(+ new URL(`../../../tests/search/fixtures/${name}`, import.meta.url),+ "utf8",+ );+ const outer = JSON.parse(fixture.slice(fixture.indexOf("[")));+ const inner = JSON.parse(outer[0][2]);+ const rows: unknown[][] = [2, 3].flatMap((i) => (Array.isArray(inner[i]) ? inner[i][0] : []));+ const flights: FlightResult[] = [];+ for (const row of rows) {+ try {+ flights.push(parseFlightRow(row));+ } catch {+ // Malformed / sponsor rows are skipped, same as the Python replay.+ }+ }+ return flights;+}++function rawLegs(name: string): unknown[][] {+ const fixture = readFileSync(+ new URL(`../../../tests/search/fixtures/${name}`, import.meta.url),+ "utf8",+ );+ const outer = JSON.parse(fixture.slice(fixture.indexOf("[")));+ const inner = JSON.parse(outer[0][2]);+ const rows: unknown[][] = [2, 3].flatMap((i) => (Array.isArray(inner[i]) ? inner[i][0] : []));+ return rows.flatMap((row) => ((row[0] as unknown[])[2] as unknown[][]) ?? []);+}++function leg(flights: FlightResult[], carrier: string, number: string): FlightLeg {+ for (const flight of flights) {+ for (const l of flight.legs) {+ if (l.airline === carrier && l.flight_number === number) return l;+ }+ }+ throw new Error(`${carrier}${number} not found in fixture`);+}++function rawRows(name: string): unknown[][] {+ const fixture = readFileSync(+ new URL(`../../../tests/search/fixtures/${name}`, import.meta.url),+ "utf8",+ );+ const outer = JSON.parse(fixture.slice(fixture.indexOf("[")));+ const inner = JSON.parse(outer[0][2]);+ return [2, 3].flatMap((i) => (Array.isArray(inner[i]) ? inner[i][0] : []));+}++/**+ * Parse a real fixture row with leg[12]/[13]/[14] overridden. Cloning a+ * genuine row keeps every other position realistic. Mirrors+ * `_synthetic_leg` in tests/search/test_amenities_decoding.py.+ */+function syntheticLeg(+ slots: unknown = null,+ seatQuality: unknown = 1,+ legroom: unknown = "31 in",+): FlightLeg {+ const row = structuredClone(rawRows("flight_search_jfk_lax_oneway_usd.bin")[0]) as unknown[];+ const l = ((row[0] as unknown[])[2] as unknown[][])[0] as unknown[];+ l[12] = slots;+ l[13] = seatQuality;+ l[14] = legroom;+ l[30] = null; // isolate leg[14] from the long-form fallback+ return parseFlightRow(row).legs[0] as FlightLeg;+}++function emptySlots(): unknown[] {+ return Array.from({ length: 12 }, () => null);+}++const FIXTURES = [+ "flight_search_jfk_lax_oneway_usd.bin",+ "flight_search_jfk_lax_eur.bin",+ "flight_search_jfk_lax_exclude_dl.bin",+ "flight_search_jfk_fra_oneworld.bin",+ "flight_search_buf_ath_min_layover_120.bin",+ "flight_search_lax_lhr_rt_biz_2a1c.bin",+];++const jfkLax = load("flight_search_jfk_lax_oneway_usd.bin");+const jfkFra = load("flight_search_jfk_fra_oneworld.bin");+const bufAth = load("flight_search_buf_ath_min_layover_120.bin");+const jfkLaxNoDl = load("flight_search_jfk_lax_exclude_dl.bin");+const laxLhrBiz = load("flight_search_lax_lhr_rt_biz_2a1c.bin");++describe("wifi tier (leg[12][11])", () => {+ test("JetBlue reports free Wi-Fi", () => {+ const l = leg(jfkLax, "B6", "123");+ expect(l.amenities?.wifi).toBe(true);+ expect(l.amenities?.wifi_tier).toBe("free");+ });++ test("Delta transcon reports free Wi-Fi", () => {+ const l = leg(jfkLax, "DL", "707");+ expect(l.amenities?.wifi).toBe(true);+ expect(l.amenities?.wifi_tier).toBe("free");+ });++ test("American widebody reports paid Wi-Fi", () => {+ const l = leg(jfkLax, "AA", "255");+ expect(l.amenities?.wifi_tier).toBe("paid");+ });++ test("British Airways reports paid Wi-Fi", () => {+ expect(leg(jfkFra, "BA", "178").amenities?.wifi_tier).toBe("paid");+ });++ test("Wi-Fi unknown when the tier slot is absent", () => {+ const l = leg(jfkFra, "BA", "904");+ expect(l.amenities?.wifi).toBeNull();+ expect(l.amenities?.wifi_tier).toBeNull();+ });++ test("Wi-Fi is not read from the power slot", () => {+ const l = leg(jfkFra, "BA", "902");+ expect(l.amenities?.power_type).toBe("usb");+ expect(l.amenities?.wifi).toBe(true);+ });+});++describe("power slots (leg[12][1..6])", () => {+ test("US major reports plug and USB", () => {+ const l = leg(jfkLax, "AA", "300");+ expect(l.amenities?.power).toBe(true);+ expect(l.amenities?.power_type).toBe("plug_and_usb");+ expect(l.amenities?.usb_power).toBe(true);+ });++ test("European short-haul reports USB only", () => {+ const l = leg(jfkFra, "BA", "904");+ expect(l.amenities?.power).toBe(true);+ expect(l.amenities?.power_type).toBe("usb");+ expect(l.amenities?.usb_power).toBe(true);+ });++ test("legacy AC-only cabin reports plug but does not deny USB", () => {+ // Slot 3 occurs 7 times across 2 carriers in the whole corpus — too+ // thin to put a `false` on a public tri-state boolean.+ const l = leg(bufAth, "AA", "1195");+ expect(l.amenities?.power).toBe(true);+ expect(l.amenities?.power_type).toBe("plug");+ expect(l.amenities?.usb_power).toBeNull();+ });++ test("power unknown when no power slot is set", () => {+ const l = leg(jfkFra, "IB", "1327");+ expect(l.amenities?.power).toBeNull();+ expect(l.amenities?.power_type).toBeNull();+ expect(l.amenities?.usb_power).toBeNull();+ });+});++describe("video slots (leg[12][8..10])", () => {+ test("JetBlue reports live TV", () => {+ const l = leg(jfkLax, "B6", "123");+ expect(l.amenities?.video_type).toBe("live_tv");+ expect(l.amenities?.in_seat_video).toBe(true);+ // A live-TV seatback usually carries on-demand content too, so the+ // absence of slot 9 is not evidence that on-demand is missing.+ expect(l.amenities?.on_demand_video).toBeNull();+ });++ test("widebody reports on-demand video", () => {+ const l = leg(jfkLax, "AA", "255");+ expect(l.amenities?.video_type).toBe("on_demand");+ expect(l.amenities?.in_seat_video).toBe(true);+ expect(l.amenities?.on_demand_video).toBe(true);+ });++ test("no-seatback fleet reports stream to device", () => {+ const l = leg(jfkLax, "AA", "117");+ expect(l.amenities?.video_type).toBe("stream_to_device");+ // The one negative these slots license: "stream to your own device"+ // is Google's way of saying there is no seatback screen.+ expect(l.amenities?.in_seat_video).toBe(false);+ // Streamed content is itself on-demand, so this stays unknown.+ expect(l.amenities?.on_demand_video).toBeNull();+ });++ test("video unknown when no video slot is set", () => {+ const l = leg(jfkFra, "BA", "904");+ expect(l.amenities?.video_type).toBeNull();+ expect(l.amenities?.in_seat_video).toBeNull();+ expect(l.amenities?.on_demand_video).toBeNull();+ });+});++describe("seat quality (leg[13]) and legroom (leg[14])", () => {+ test("above-average economy seat", () => {+ const l = leg(jfkLax, "B6", "123");+ expect(l.amenities?.legroom_rating).toBe(3);+ expect(l.amenities?.seat_quality).toBe("above_average");+ expect(l.amenities?.legroom_inches).toBe(33);+ });++ test("average economy seat", () => {+ const l = leg(jfkLax, "AA", "300");+ expect(l.amenities?.seat_quality).toBe("average");+ expect(l.amenities?.legroom_inches).toBe(31);+ });++ test("below-average economy seat", () => {+ const l = leg(jfkFra, "BA", "904");+ expect(l.amenities?.seat_quality).toBe("below_average");+ expect(l.amenities?.legroom_inches).toBe(29);+ });++ test("lie-flat business seat has no published pitch", () => {+ const l = leg(laxLhrBiz, "EI", "68");+ expect(l.amenities?.legroom_rating).toBe(5);+ expect(l.amenities?.seat_quality).toBe("lie_flat");+ expect(l.amenities?.legroom_inches).toBeNull();+ });++ test("domestic first is a recliner", () => {+ const l = leg(jfkLaxNoDl, "AA", "1154");+ expect(l.amenities?.legroom_rating).toBe(8);+ expect(l.amenities?.seat_quality).toBe("recliner");+ });+});++describe("cabin (leg[16])", () => {+ test("economy leg", () => {+ expect(leg(jfkLax, "B6", "123").cabin).toBe(SeatType.ECONOMY);+ });++ test("business leg", () => {+ expect(leg(laxLhrBiz, "EI", "68").cabin).toBe(SeatType.BUSINESS);+ });++ test("premium economy leg", () => {+ expect(leg(laxLhrBiz, "EI", "172").cabin).toBe(SeatType.PREMIUM_ECONOMY);+ });++ test("first leg", () => {+ expect(leg(jfkLaxNoDl, "AA", "1154").cabin).toBe(SeatType.FIRST);+ });++ test("cabin is per leg, not per itinerary", () => {+ expect(leg(laxLhrBiz, "BA", "833").cabin).toBe(SeatType.ECONOMY);+ });++ test("cabin tracks the fare, not the aircraft", () => {+ // AA 1209 (ORD-LAX, 737 MAX 8) appears as both an economy row and a+ // first row in this fixture.+ const seen = new Set(+ jfkLaxNoDl+ .flatMap((flight) => flight.legs)+ .filter((l) => l.airline === "AA" && l.flight_number === "1209")+ .map((l) => `${l.cabin}:${l.amenities?.seat_quality}`),+ );+ expect(seen).toEqual(new Set([`${SeatType.ECONOMY}:average`, `${SeatType.FIRST}:recliner`]));+ });+});++describe("unobserved slots", () => {+ for (const slot of [2, 4, 6]) {+ test(`"some seats" power slot ${slot} does not assert power`, () => {+ // Slots 2/4/6 occur zero times in 481 legs; nothing is inferred.+ const slots = emptySlots();+ slots[slot] = true;+ const a = syntheticLeg(slots).amenities;+ expect(a?.power).toBeNull();+ expect(a?.power_type).toBeNull();+ expect(a?.usb_power).toBeNull();+ });+ }++ test("unknown Wi-Fi tier code still reports Wi-Fi", () => {+ const slots = emptySlots();+ slots[11] = 1;+ const a = syntheticLeg(slots).amenities;+ expect(a?.wifi).toBe(true);+ expect(a?.wifi_tier).toBeNull();+ });++ test("unknown seat-quality code keeps the raw rating", () => {+ const a = syntheticLeg(emptySlots(), 9).amenities;+ expect(a?.legroom_rating).toBe(9);+ expect(a?.seat_quality).toBeNull();+ });++ test("first set power slot wins even when unlabelled", () => {+ // Impossible per the corpus, but Python and TypeScript must agree:+ // both scan 1..6 in wire order and refuse to skip past a set slot+ // they cannot name.+ const slots = emptySlots();+ slots[2] = true;+ slots[3] = true;+ const a = syntheticLeg(slots).amenities;+ expect(a?.power).toBeNull();+ expect(a?.power_type).toBeNull();+ expect(a?.usb_power).toBeNull();+ });+});++describe("slot value types", () => {+ for (const flag of [true, 1]) {+ test(`${JSON.stringify(flag)} counts as a set slot`, () => {+ const slots = emptySlots();+ slots[1] = flag;+ expect(syntheticLeg(slots).amenities?.power_type).toBe("plug_and_usb");+ });+ }++ for (const value of [false, 0, -1, 1.5, "1", null]) {+ test(`${JSON.stringify(value)} does not set a slot`, () => {+ const slots = emptySlots();+ slots[1] = value;+ expect(syntheticLeg(slots).amenities?.power).toBeNull();+ });+ }++ // 2.0 is deliberately absent: JavaScript has no float/int distinction for+ // whole numbers (JSON.parse("2.0") === 2), so it cannot be rejected here+ // the way Python's isinstance(v, int) rejects the float 2.0. Every+ // genuinely non-integral value behaves identically in both ports.+ for (const value of [2.5, "2", true]) {+ test(`Wi-Fi code ${JSON.stringify(value)} is ignored`, () => {+ const slots = emptySlots();+ slots[11] = value;+ const a = syntheticLeg(slots).amenities;+ expect(a?.wifi).toBeNull();+ expect(a?.wifi_tier).toBeNull();+ });+ }+});++describe("legroom inches parsing", () => {+ const cases: [string, number | null][] = [+ ["31 in", 31],+ ["31 inches", 31],+ ["7 in", 7],+ // Non-ASCII digits are not seat pitches. Python's str.isdigit() is+ // True for these, so the shared guard must be ASCII-only.+ ["² in", null],+ ["١٢ in", null],+ ["", null],+ ["lie flat", null],+ ["0 in", null],+ ["-3 in", null],+ ];+ for (const [text, expected] of cases) {+ test(`parses ${JSON.stringify(text)} as ${expected}`, () => {+ expect(syntheticLeg(emptySlots(), 1, text).amenities?.legroom_inches).toBe(expected);+ });+ }++ test("unparseable legroom does not drop the row", () => {+ const row = structuredClone(rawRows("flight_search_jfk_lax_oneway_usd.bin")[0]) as unknown[];+ (((row[0] as unknown[])[2] as unknown[][])[0] as unknown[])[14] = "² in";+ const flight = parseFlightRow(row);+ expect(flight.legs.length).toBeGreaterThan(0);+ expect(flight.legs[0]?.amenities?.legroom_inches).toBeNull();+ });+});++describe("corpus invariants", () => {+ for (const [label, group] of [+ ["power 1..6", [1, 2, 3, 4, 5, 6]],+ ["video 8..10", [8, 9, 10]],+ ] as [string, number[]][]) {+ test(`${label} slots are mutually exclusive`, () => {+ for (const name of FIXTURES) {+ for (const fl of rawLegs(name)) {+ const slots = fl[12];+ if (!Array.isArray(slots)) continue;+ const on = group.filter((i) => slots[i]);+ expect(on.length).toBeLessThanOrEqual(1);+ }+ }+ });+ }++ test("the Wi-Fi slot is never a bool", () => {+ for (const name of FIXTURES) {+ for (const fl of rawLegs(name)) {+ const slots = fl[12];+ if (!Array.isArray(slots)) continue;+ const tier = slots[11];+ if (tier == null) continue;+ expect(typeof tier).toBe("number");+ }+ }+ });+});++describe("slot flag encoding", () => {+ test("accepts the public page's integer flags as well as booleans", () => {+ // The RPC payload uses JSON booleans; the public travel page encodes+ // the same slots as 1.+ const rows = rawLegs("flight_search_jfk_lax_oneway_usd.bin");+ const fixture = readFileSync(+ new URL(+ "../../../tests/search/fixtures/flight_search_jfk_lax_oneway_usd.bin",+ import.meta.url,+ ),+ "utf8",+ );+ const outer = JSON.parse(fixture.slice(fixture.indexOf("[")));+ const inner = JSON.parse(outer[0][2]);+ const row = structuredClone(inner[2][0][0]) as unknown[];+ const detail = row[0] as unknown[];+ const l = (detail[2] as unknown[][])[0] as unknown[];+ const slots: unknown[] = Array.from({ length: 12 }, () => null);+ slots[1] = 1;+ slots[9] = 1;+ slots[11] = 2;+ l[12] = slots;+ l[13] = 3;+ expect(rows.length).toBeGreaterThan(0);+ const parsed = parseFlightRow(row);+ expect(parsed.legs[0]?.amenities?.power_type).toBe("plug_and_usb");+ expect(parsed.legs[0]?.amenities?.video_type).toBe("on_demand");+ expect(parsed.legs[0]?.amenities?.wifi_tier).toBe("free");+ });+});diff --git a/fli/cli/utils.py b/fli/cli/utils.pyindex db0ea50..fa079a4 100644--- a/fli/cli/utils.py+++ b/fli/cli/utils.py@@ -199,6 +199,9 @@ def serialize_flight_leg(leg: Any) -> dict[str, Any]:payload["aircraft"] = leg.aircraftif getattr(leg, "legroom", None):payload["legroom"] = leg.legroom+ cabin_name = getattr(getattr(leg, "cabin", None), "name", None)+ if isinstance(cabin_name, str):+ payload["cabin"] = cabin_nameif getattr(leg, "overnight", False):payload["overnight"] = Trueif getattr(leg, "operating_airline", None) is not None:diff --git a/fli/mcp/server.py b/fli/mcp/server.pyindex 289e8df..82621c4 100755--- a/fli/mcp/server.py+++ b/fli/mcp/server.py@@ -409,6 +409,12 @@ def _serialize_flight_leg(leg: Any) -> dict[str, Any]:out["aircraft"] = leg.aircraftif getattr(leg, "legroom", None):out["legroom"] = leg.legroom+ cabin_name = getattr(getattr(leg, "cabin", None), "name", None)+ if isinstance(cabin_name, str):+ # Report the SeatType member name (ECONOMY / BUSINESS / ...) so it+ # matches the `cabin_class` tool parameter rather than Google's+ # numeric code.+ out["cabin"] = cabin_nameif getattr(leg, "overnight", False):out["overnight"] = Trueamenities = getattr(leg, "amenities", None)diff --git a/fli/models/__init__.py b/fli/models/__init__.pyindex 6e4af71..2e8d161 100644--- a/fli/models/__init__.py+++ b/fli/models/__init__.py@@ -16,11 +16,15 @@ from .google_flights import (LayoverRestrictions,MaxStops,PassengerInfo,+ PowerType,PriceLimit,+ SeatQuality,SeatType,SortBy,TimeRestrictions,TripType,+ VideoType,+ WifiTier,)from .names import display_name@@ -43,9 +47,13 @@ __all__ = ["LayoverRestrictions","MaxStops","PassengerInfo",+ "PowerType","PriceLimit",+ "SeatQuality","SeatType","SortBy","TimeRestrictions","TripType",+ "VideoType",+ "WifiTier",]diff --git a/fli/models/google_flights/__init__.py b/fli/models/google_flights/__init__.pyindex 7e63ef4..5c0cfc9 100644--- a/fli/models/google_flights/__init__.py+++ b/fli/models/google_flights/__init__.py@@ -12,11 +12,15 @@ from .base import (LayoverRestrictions,MaxStops,PassengerInfo,+ PowerType,PriceLimit,+ SeatQuality,SeatType,SortBy,TimeRestrictions,TripType,+ VideoType,+ WifiTier,)from .dates import DateSearchFiltersfrom .flights import FlightSearchFilters@@ -39,9 +43,13 @@ __all__ = ["LayoverRestrictions","MaxStops","PassengerInfo",+ "PowerType","PriceLimit",+ "SeatQuality","SeatType","SortBy","TimeRestrictions","TripType",+ "VideoType",+ "WifiTier",]diff --git a/fli/models/google_flights/base.py b/fli/models/google_flights/base.pyindex 918449f..9f828ad 100644--- a/fli/models/google_flights/base.py+++ b/fli/models/google_flights/base.py@@ -6,6 +6,7 @@ Models are designed to match Google Flights' APIs while providing a clean pythonfrom datetime import date, datetime, timedelta, timezonefrom enum import Enum+from typing import Literalfrom pydantic import (BaseModel,@@ -258,13 +259,55 @@ class LayoverRestrictions(BaseModel):max_duration: PositiveInt | None = None+#: In-seat power flavour decoded from the ``leg[12]`` power slot group.+PowerType = Literal["plug_and_usb", "plug", "usb"]++#: In-flight entertainment flavour decoded from the ``leg[12]`` video group.+VideoType = Literal["live_tv", "on_demand", "stream_to_device"]++#: Whether Google flags the leg's Wi-Fi as complimentary or chargeable.+WifiTier = Literal["free", "paid"]++#: Human-readable label for Google's ``leg[13]`` seat-quality code.+#:+#: These are labels, not an ordered score: "average"/"below_average"/+#: "above_average" describe an economy-style pitch, while the remaining+#: four name a seat *product*. The code tracks the fare's cabin rather+#: than the airframe — in the captured fixtures AA 1209 (ORD-LAX, 737+#: MAX 8) appears twice, as "average" in economy and "recliner" in first.+SeatQuality = Literal[+ "average",+ "below_average",+ "above_average",+ "extra_reclining",+ "lie_flat",+ "lie_flat_suite_with_door",+ "recliner",+]++class Amenities(BaseModel):"""Per-leg amenities reported by Google Flights.Boolean fields are tri-state (`True`, `False`, or `None` when Google didnot publish that signal). ``legroom_rating`` is Google's seat-qualitycode from ``leg[13]``, or ``None`` when unavailable; it is not an ordered- numeric score or the Wi-Fi tier.+ numeric score or the Wi-Fi tier. ``seat_quality`` is the decoded label+ for that same code and is ``None`` for codes we have not confirmed.++ The optional detail fields (``wifi_tier``, ``power_type``,+ ``video_type``, ``seat_quality``, ``legroom_inches``) refine the+ booleans above rather than replacing them: e.g. ``power=True`` plus+ ``power_type="usb"`` means "charging available, USB only".++ Google never publishes an explicit "no" for any of these amenities —+ the wire format only ever sets a flag or omits it — so ``False`` is+ always an inference and is used exactly once: ``in_seat_video`` is+ ``False`` when ``video_type == "stream_to_device"``, which is+ Google's way of saying the aircraft has no seatback screen. Every+ other unknown stays ``None``, including ``usb_power`` for a+ plug-only cabin and ``on_demand_video`` for a live-TV or+ stream-to-device leg."""wifi: bool | None = None@@ -274,6 +317,15 @@ class Amenities(BaseModel):on_demand_video: bool | None = Nonelegroom_rating: NonNegativeInt | None = None+ # Optional detail — populated only for slot values confirmed against+ # captured responses; left None when Google publishes a code we have+ # not verified, so callers never see a confidently wrong label.+ wifi_tier: WifiTier | None = None+ power_type: PowerType | None = None+ video_type: VideoType | None = None+ seat_quality: SeatQuality | None = None+ legroom_inches: PositiveInt | None = None+class Layover(BaseModel):"""Layover info between two flight legs.@@ -320,6 +372,9 @@ class FlightLeg(BaseModel):amenities: Amenities | None = Noneovernight: bool = Falseco2_emissions_g: NonNegativeInt | None = None+ #: Cabin actually flown on this leg, from ``leg[16]``. Per-leg, so a+ #: business itinerary can still show an economy connecting leg.+ cabin: SeatType | None = Noneclass BookingOption(BaseModel):diff --git a/fli/search/_decoders.py b/fli/search/_decoders.pyindex 2125995..cade369 100644--- a/fli/search/_decoders.py+++ b/fli/search/_decoders.py@@ -25,6 +25,7 @@ from fli.models import (FlightLeg,FlightResult,Layover,+ SeatType,)from fli.search._helpers import as_bool, as_int, as_non_negative_int, as_str, safe_get@@ -85,12 +86,13 @@ def _parse_leg(fl: list) -> FlightLeg:op_code = safe_get(airline_info, 2)operating_airline = _safe_airline(op_code) if op_code else None- amenities = _parse_amenities(safe_get(fl, 12), safe_get(fl, 13))aircraft = as_str(safe_get(fl, 17))legroom_short = as_str(safe_get(fl, 14))legroom_long = as_str(safe_get(fl, 30))+ amenities = _parse_amenities(safe_get(fl, 12), safe_get(fl, 13), legroom_short or legroom_long)overnight = as_bool(safe_get(fl, 19)) or Falseco2_emissions_g = as_non_negative_int(safe_get(fl, 31))+ cabin = _parse_cabin(safe_get(fl, 16))return FlightLeg(airline=airline,@@ -110,30 +112,174 @@ def _parse_leg(fl: list) -> FlightLeg:amenities=amenities,overnight=overnight,co2_emissions_g=co2_emissions_g,+ cabin=cabin,)-def _parse_amenities(slots: Any, seat_quality: Any = None) -> Amenities | None:- """Decode amenities at ``leg[12]`` and the seat-quality code at ``leg[13]``.+def _parse_cabin(code: Any) -> SeatType | None:+ """Decode the per-leg cabin code at ``leg[16]`` into a :class:`SeatType`.- ``leg[12][11]`` is the Wi-Fi tier, not a legroom rating. Seat quality- may be present even when the amenities array is missing.+ Google uses the same 1..4 numbering here as in the request filters+ (1 economy, 2 premium economy, 3 business, 4 first). Unknown codes+ return None rather than raising — the leg is still usable.+ """+ value = as_non_negative_int(code)+ if value is None:+ return None+ try:+ return SeatType(value)+ except ValueError:+ logger.debug("Unknown cabin code %r at leg[16]", value)+ return None+++# --- leg[12] amenity slot map (issue #217) --------------------------------+#+# ``leg[12]`` is a sparse array of amenity flags, trailing nulls trimmed.+# Two mutually-exclusive groups plus a Wi-Fi tier code were confirmed by+# tabulating all 481 leg instances across the captured fixtures (plus+# three live public-page captures) against published fleet facts:+#+# slots 1..6 power group — exactly one is ever set on a leg.+# slots 8..10 video group — exactly one is ever set on a leg.+# slot 11 Wi-Fi tier code (an int, never a bool).+#+# Slots 2, 4 and 6 are reported to be "some seats only" variants of 1, 3+# and 5, and slot 11 == 1 is reported to mean "Wi-Fi, tier unknown", but+# none of those values occurs anywhere in the corpus. Nothing is inferred+# from them: an unobserved slot yields None, never a guessed value.+#+# No slot in the corpus ever holds JSON ``false``, so every ``False`` this+# decoder emits is an inference. Only one is made — see+# ``in_seat_video`` in :func:`_parse_amenities`.++#: Power slots whose flavour is confirmed.+_POWER_SLOTS: dict[int, str] = {1: "plug_and_usb", 3: "plug", 5: "usb"}+#: Every index in the power group, scanned in wire order. Includes the+#: unobserved 2/4/6 "some seats" variants deliberately: the first *set*+#: slot wins even when it is one we cannot label, so a payload that ever+#: does set one yields "unknown" rather than skipping ahead to a slot we+#: can name and reporting something Google did not say.+_POWER_GROUP: tuple[int, ...] = (1, 2, 3, 4, 5, 6)+#: Video slots, in wire order (first match wins).+_VIDEO_SLOTS: dict[int, str] = {8: "live_tv", 9: "on_demand", 10: "stream_to_device"}+#: Video products delivered on a seatback screen rather than to a phone.+_SEATBACK_VIDEO = frozenset({"live_tv", "on_demand"})+#: Position of the Wi-Fi tier code within ``leg[12]``.+_WIFI_TIER_SLOT = 11+#: Confirmed Wi-Fi tier codes.+_WIFI_TIERS: dict[int, str] = {2: "free", 3: "paid"}+#: Confirmed ``leg[13]`` seat-quality codes. Code 9 ("angled flat") is+#: reported but unobserved, so it deliberately has no label here.+_SEAT_QUALITY: dict[int, str] = {+ 1: "average",+ 2: "below_average",+ 3: "above_average",+ 4: "extra_reclining",+ 5: "lie_flat",+ 6: "lie_flat_suite_with_door",+ 8: "recliner",+}+++def _slot_on(slots: Any, index: int) -> bool:+ """Return True when ``slots[index]`` is a set flag.++ Google's RPC payload encodes these flags as JSON booleans while the+ public travel page encodes the same fields as ``1``; accept both and+ treat every other value (including ``0`` and strings) as unset.+ """+ value = safe_get(slots, index)+ if isinstance(value, bool):+ return value+ return isinstance(value, int) and value > 0+++def _first_slot(slots: Any, indexes: Any) -> int | None:+ """Return the first index in ``indexes`` whose slot is set, else None."""+ return next((i for i in indexes if _slot_on(slots, i)), None)- Return None when neither source carries a usable value.++def _parse_legroom_inches(*legroom_strings: Any) -> int | None:+ """Pull the integer seat pitch out of ``"31 in"`` / ``"31 inches"``.++ ``str.isdigit()`` alone is not a safe guard: it is True for+ superscripts like ``"²"``, which ``int()`` then rejects with a+ ValueError. This runs inside :func:`_parse_leg`, so that exception+ would propagate out of :func:`parse_flight_row` and silently drop the+ entire flight row. Restrict to plain ASCII digits, which also keeps+ this identical to the TypeScript port's ASCII-only regex."""- wifi = as_bool(safe_get(slots, 1))- power = as_bool(safe_get(slots, 5))- on_demand_video = as_bool(safe_get(slots, 9))+ for text in legroom_strings:+ if not isinstance(text, str):+ continue+ head = text.split(" ", 1)[0]+ if head.isascii() and head.isdigit():+ inches = int(head)+ if inches > 0:+ return inches+ return None+++def _parse_amenities(slots: Any, seat_quality: Any = None, legroom: Any = None) -> Amenities | None:+ """Decode amenities at ``leg[12]``, seat quality at ``leg[13]``, pitch at ``leg[14]``.++ ``leg[12][11]`` is the Wi-Fi tier, not a legroom rating, and slot 1 is+ a power flag rather than Wi-Fi — see ``_POWER_SLOTS`` above. Seat+ quality and legroom may be present even when the amenities array is+ missing.++ Return None when no source carries a usable value.+ """+ # Only a slot whose meaning the corpus confirms may set ``power``; an+ # unlabelled slot (2/4/6, never observed) leaves every power field+ # unknown rather than asserting "there is power, flavour unknown".+ power_slot = _first_slot(slots, _POWER_GROUP)+ power_type = _POWER_SLOTS.get(power_slot) if power_slot is not None else None+ power = True if power_type is not None else None+ # ``power_type == "plug"`` is the AC-outlet-only variant, but it rests+ # on 7 legs from 2 carriers in the whole corpus — far too thin to put+ # a False on a public tri-state. The distinction survives losslessly+ # in ``power_type``; ``usb_power`` only ever says True or "unknown".+ usb_power = True if power_type in ("plug_and_usb", "usb") else None++ video_slot = _first_slot(slots, _VIDEO_SLOTS)+ video_type = _VIDEO_SLOTS.get(video_slot) if video_slot is not None else None+ # INFERENCE: "stream to your own device" is Google's way of saying the+ # aircraft has no seatback screen — true of every slot-10 fleet in the+ # corpus (Alaska, AA 737/A321 Sharklets, every regional jet) — so it+ # is the one negative these slots license. Nothing else is inferred:+ # a live-TV seatback normally carries on-demand content too, and+ # streamed content is itself on-demand, so the absence of slot 9 is+ # not evidence that on-demand is unavailable.+ in_seat_video = None if video_type is None else video_type in _SEATBACK_VIDEO+ on_demand_video = True if video_type == "on_demand" else None++ wifi_code = as_non_negative_int(safe_get(slots, _WIFI_TIER_SLOT))+ wifi = True if wifi_code else None+ wifi_tier = _WIFI_TIERS.get(wifi_code) if wifi_code else None+legroom_rating = as_non_negative_int(seat_quality)- if wifi is None and power is None and on_demand_video is None and legroom_rating is None:+ seat_quality_label = _SEAT_QUALITY.get(legroom_rating) if legroom_rating is not None else None+ # ``legroom_inches`` is derived from a string the leg already exposes+ # as ``legroom``/``legroom_short``, so on its own it is not enough to+ # materialise an Amenities object — that keeps "no amenities" meaning+ # the same thing it did before this decoder was corrected.+ if wifi is None and power is None and video_type is None and legroom_rating is None:return None+ legroom_inches = _parse_legroom_inches(legroom)return Amenities(wifi=wifi,power=power,- usb_power=None,- in_seat_video=None,+ usb_power=usb_power,+ in_seat_video=in_seat_video,on_demand_video=on_demand_video,legroom_rating=legroom_rating,+ wifi_tier=wifi_tier,+ power_type=power_type,+ video_type=video_type,+ seat_quality=seat_quality_label,+ legroom_inches=legroom_inches,)diff --git a/tests/mcp/test_mcp_server_unit.py b/tests/mcp/test_mcp_server_unit.pyindex d64fdab..bf4cf8a 100644--- a/tests/mcp/test_mcp_server_unit.py+++ b/tests/mcp/test_mcp_server_unit.py@@ -68,6 +68,7 @@ class TestSerializeFlightLeg:leg.legroom = Noneleg.overnight = Falseleg.amenities = None+ leg.cabin = Nonefor k, v in overrides.items():setattr(leg, k, v)return leg@@ -95,6 +96,13 @@ class TestSerializeFlightLeg:assert "operating_airline" not in resultassert "aircraft" not in resultassert "legroom" not in result+ assert "cabin" not in result++ def test_cabin_serialized_as_seat_type_name(self):+ from fli.models import SeatType++ leg = self._make_leg(cabin=SeatType.BUSINESS)+ assert _serialize_flight_leg(leg)["cabin"] == "BUSINESS"def test_overnight_true_included(self):leg = self._make_leg(overnight=True)diff --git a/tests/search/test_amenities_decoding.py b/tests/search/test_amenities_decoding.pynew file mode 100644index 0000000..0bce583--- /dev/null+++ b/tests/search/test_amenities_decoding.py@@ -0,0 +1,453 @@+"""Fixture-backed tests for per-leg amenity decoding (issue #217).++Every expectation below is pinned to a *named* flight in a captured+Google Flights response under ``tests/search/fixtures/``, so the slot+mapping is asserted against real wire data rather than a synthetic+guess. The mapping itself was verified by tabulating ``leg[12][0..11]``,+``leg[13]``, ``leg[14]`` and ``leg[16]`` across all 481 leg instances in+those fixtures and cross-checking against published fleet facts:++- slots 1..6 are a mutually-exclusive *power* group (no leg in the corpus+ has two of them set). Slot 1 is seen on US majors (AC outlet + USB,+ n=401), slot 5 on European short-haul and ULCCs (USB only, n=46),+ slot 3 on legacy AC-only cabins (AA A319, UA 737 — only n=7, which is+ why it drives an opt-in label but never a ``False``). Slots 2, 4 and 6+ never occur at all.+- slots 8..10 are a mutually-exclusive *video* group. Slot 8 is seen only+ on JetBlue and Delta domestic narrowbodies (live TV), slot 9 on+ widebodies and AA's transcon A321neo (on-demand), slot 10 on fleets+ with no seatback screens at all (Alaska, AA 737/A321 Sharklets,+ regional jets) — i.e. stream-to-your-device.+- slot 11 is a Wi-Fi *tier* code, never a bool: 2 on carriers with free+ Wi-Fi (JetBlue, Delta), 3 on carriers that charge (BA, AF, LH, Alaska).+"""++from __future__ import annotations++import copy+import json+from pathlib import Path++import pytest++from fli.models import SeatType+from fli.search._decoders import parse_flight_row++FIXTURE_DIR = Path(__file__).parent / "fixtures"+++def _raw_rows(name: str) -> list:+ body = (FIXTURE_DIR / name).read_text()+ inner = json.loads(json.loads(body.lstrip(")]}'"))[0][2])+ return [item for i in (2, 3) if isinstance(inner[i], list) for item in inner[i][0]]+++def _synthetic_leg(slots=None, seat_quality=1, legroom="31 in"):+ """Parse a real fixture row with leg[12]/[13]/[14] overridden.++ Cloning a genuine row keeps every other position realistic, so these+ edge-case tests exercise the amenity decoding without hand-rolling a+ whole response.+ """+ row = copy.deepcopy(_raw_rows("flight_search_jfk_lax_oneway_usd.bin")[0])+ leg = row[0][2][0]+ leg[12] = slots+ leg[13] = seat_quality+ leg[14] = legroom+ leg[30] = None # isolate leg[14] from the long-form fallback+ return parse_flight_row(row).legs[0]+++def _replay(name: str) -> list:+ body = (FIXTURE_DIR / name).read_text()+ outer = json.loads(body.lstrip(")]}'"))+ inner = json.loads(outer[0][2])+ rows = [item for i in (2, 3) if isinstance(inner[i], list) for item in inner[i][0]]+ flights = []+ for row in rows:+ try:+ flights.append(parse_flight_row(row))+ except (AttributeError, KeyError, ValueError, TypeError):+ continue+ return flights+++def _leg(flights: list, carrier: str, number: str):+ for flight in flights:+ for leg in flight.legs:+ if leg.airline.name == carrier and leg.flight_number == number:+ return leg+ raise AssertionError(f"{carrier}{number} not found in fixture")++[email protected](scope="module")+def jfk_lax():+ return _replay("flight_search_jfk_lax_oneway_usd.bin")++[email protected](scope="module")+def jfk_fra():+ return _replay("flight_search_jfk_fra_oneworld.bin")++[email protected](scope="module")+def buf_ath():+ return _replay("flight_search_buf_ath_min_layover_120.bin")++[email protected](scope="module")+def jfk_lax_no_dl():+ return _replay("flight_search_jfk_lax_exclude_dl.bin")++[email protected](scope="module")+def lax_lhr_biz():+ return _replay("flight_search_lax_lhr_rt_biz_2a1c.bin")+++class TestWifiTier:+ """``leg[12][11]`` is the Wi-Fi tier — slot 1 is power, not Wi-Fi."""++ def test_jetblue_reports_free_wifi(self, jfk_lax):+ # B6 123 (A320): slot 11 == 2. JetBlue is free Wi-Fi fleet-wide.+ leg = _leg(jfk_lax, "B6", "123")+ assert leg.amenities.wifi is True+ assert leg.amenities.wifi_tier == "free"++ def test_delta_transcon_reports_free_wifi(self, jfk_lax):+ leg = _leg(jfk_lax, "DL", "707")+ assert leg.amenities.wifi is True+ assert leg.amenities.wifi_tier == "free"++ def test_american_widebody_reports_paid_wifi(self, jfk_lax):+ # AA 255 (777) carries slot 11 == 3 while AA's narrowbodies carry 2.+ leg = _leg(jfk_lax, "AA", "255")+ assert leg.amenities.wifi is True+ assert leg.amenities.wifi_tier == "paid"++ def test_british_airways_reports_paid_wifi(self, jfk_fra):+ leg = _leg(jfk_fra, "BA", "178")+ assert leg.amenities.wifi is True+ assert leg.amenities.wifi_tier == "paid"++ def test_wifi_unknown_when_tier_slot_absent(self, jfk_fra):+ # BA 904 (A319) stops at slot 5 — no Wi-Fi tier published.+ leg = _leg(jfk_fra, "BA", "904")+ assert leg.amenities.wifi is None+ assert leg.amenities.wifi_tier is None++ def test_wifi_not_read_from_the_power_slot(self, jfk_fra):+ # BA 902 has no power slot 1 but does publish a Wi-Fi tier; the old+ # decoder read slot 1 and reported wifi=None here.+ leg = _leg(jfk_fra, "BA", "902")+ assert leg.amenities.power_type == "usb"+ assert leg.amenities.wifi is True+++class TestPowerSlots:+ """Slots 1..6 form the power group; first truthy slot wins."""++ def test_us_major_reports_plug_and_usb(self, jfk_lax):+ leg = _leg(jfk_lax, "AA", "300")+ assert leg.amenities.power is True+ assert leg.amenities.power_type == "plug_and_usb"+ assert leg.amenities.usb_power is True++ def test_jetblue_reports_plug_and_usb(self, jfk_lax):+ leg = _leg(jfk_lax, "B6", "123")+ assert leg.amenities.power is True+ assert leg.amenities.power_type == "plug_and_usb"+ assert leg.amenities.usb_power is True++ def test_european_shorthaul_reports_usb_only(self, jfk_fra):+ # BA 904 (A319) — USB-A charging, no AC outlet.+ leg = _leg(jfk_fra, "BA", "904")+ assert leg.amenities.power is True+ assert leg.amenities.power_type == "usb"+ assert leg.amenities.usb_power is True++ def test_legacy_ac_only_cabin_reports_plug(self, buf_ath):+ """Slot 3 labels the leg "plug" but must not assert "no USB".++ Slot 3 occurs 7 times across 2 carriers in the whole corpus — too+ thin to put a ``False`` on a public tri-state boolean, so+ ``usb_power`` stays None and the detail lives in ``power_type``.+ """+ leg = _leg(buf_ath, "AA", "1195")+ assert leg.amenities.power is True+ assert leg.amenities.power_type == "plug"+ assert leg.amenities.usb_power is None++ def test_power_unknown_when_no_power_slot_set(self, jfk_fra):+ # IB 1327 (CRJ1000) publishes only the video slot.+ leg = _leg(jfk_fra, "IB", "1327")+ assert leg.amenities.power is None+ assert leg.amenities.power_type is None+ assert leg.amenities.usb_power is None+++class TestVideoSlots:+ """Slots 8..10 form the video group; first truthy slot wins."""++ def test_jetblue_reports_live_tv(self, jfk_lax):+ leg = _leg(jfk_lax, "B6", "123")+ assert leg.amenities.video_type == "live_tv"+ assert leg.amenities.in_seat_video is True+ # A live-TV seatback usually carries on-demand content too, so the+ # absence of slot 9 is not evidence that on-demand is missing.+ assert leg.amenities.on_demand_video is None++ def test_widebody_reports_on_demand(self, jfk_lax):+ leg = _leg(jfk_lax, "AA", "255")+ assert leg.amenities.video_type == "on_demand"+ assert leg.amenities.in_seat_video is True+ assert leg.amenities.on_demand_video is True++ def test_no_seatback_fleet_reports_stream_to_device(self, jfk_lax):+ # AA 117 flies the A321 (Sharklets) — streaming only, no screens,+ # unlike the A321neo transcon aircraft on AA 300.+ leg = _leg(jfk_lax, "AA", "117")+ assert leg.amenities.video_type == "stream_to_device"+ # "stream to your own device" is the plain statement that there is+ # no seatback screen — the one negative the slot licenses.+ assert leg.amenities.in_seat_video is False+ # Streamed content is itself on-demand, so this stays unknown.+ assert leg.amenities.on_demand_video is None++ def test_video_unknown_when_no_video_slot_set(self, jfk_fra):+ leg = _leg(jfk_fra, "BA", "904")+ assert leg.amenities.video_type is None+ assert leg.amenities.in_seat_video is None+ assert leg.amenities.on_demand_video is None+++class TestSeatQualityAndLegroom:+ """``leg[13]`` labels the seat; ``leg[14]`` carries pitch in inches."""++ def test_above_average_economy_seat(self, jfk_lax):+ leg = _leg(jfk_lax, "B6", "123")+ assert leg.amenities.legroom_rating == 3+ assert leg.amenities.seat_quality == "above_average"+ assert leg.amenities.legroom_inches == 33++ def test_average_economy_seat(self, jfk_lax):+ leg = _leg(jfk_lax, "AA", "300")+ assert leg.amenities.legroom_rating == 1+ assert leg.amenities.seat_quality == "average"+ assert leg.amenities.legroom_inches == 31++ def test_below_average_economy_seat(self, jfk_fra):+ leg = _leg(jfk_fra, "BA", "904")+ assert leg.amenities.legroom_rating == 2+ assert leg.amenities.seat_quality == "below_average"+ assert leg.amenities.legroom_inches == 29++ def test_lie_flat_business_seat(self, lax_lhr_biz):+ # EI 68 (A330) is the long-haul business leg; Google publishes no+ # pitch in inches for lie-flat seats.+ leg = _leg(lax_lhr_biz, "EI", "68")+ assert leg.amenities.legroom_rating == 5+ assert leg.amenities.seat_quality == "lie_flat"+ assert leg.amenities.legroom_inches is None++ def test_domestic_first_recliner(self, jfk_lax_no_dl):+ # AA 1154 (DFW-LAX) appears only as a first-class row in this+ # fixture: a domestic recliner, with no pitch published.+ leg = _leg(jfk_lax_no_dl, "AA", "1154")+ assert leg.amenities.legroom_rating == 8+ assert leg.amenities.seat_quality == "recliner"+ assert leg.amenities.legroom_inches is None++ def test_flagship_business_lie_flat(self, jfk_lax_no_dl):+ # AA 177 is the JFK transcon A321T with a true lie-flat cabin.+ leg = _leg(jfk_lax_no_dl, "AA", "177")+ assert leg.amenities.seat_quality == "lie_flat"+++class TestCabin:+ """``leg[16]`` is the per-leg cabin, matching ``SeatType``."""++ def test_economy_leg(self, jfk_lax):+ assert _leg(jfk_lax, "B6", "123").cabin is SeatType.ECONOMY++ def test_business_leg(self, lax_lhr_biz):+ assert _leg(lax_lhr_biz, "EI", "68").cabin is SeatType.BUSINESS++ def test_premium_economy_leg(self, lax_lhr_biz):+ assert _leg(lax_lhr_biz, "EI", "172").cabin is SeatType.PREMIUM_ECONOMY++ def test_first_leg(self, jfk_lax_no_dl):+ assert _leg(jfk_lax_no_dl, "AA", "1154").cabin is SeatType.FIRST++ def test_cabin_is_per_leg_not_per_itinerary(self, lax_lhr_biz):+ # The DUB->LHR partner leg of a business itinerary is plain economy.+ assert _leg(lax_lhr_biz, "BA", "833").cabin is SeatType.ECONOMY++ def test_cabin_tracks_the_fare_not_the_aircraft(self, jfk_lax_no_dl):+ """The same physical flight appears once per bookable cabin.++ AA 1209 (ORD-LAX, 737 MAX 8) shows up twice in this fixture: an+ economy row and a first row. The cabin code and the seat-quality+ code move together, which is what proves ``leg[16]`` describes the+ fare's cabin rather than the airframe.+ """+ cabins = {+ (leg.cabin, leg.amenities.seat_quality)+ for flight in jfk_lax_no_dl+ for leg in flight.legs+ if leg.airline.name == "AA" and leg.flight_number == "1209"+ }+ assert cabins == {+ (SeatType.ECONOMY, "average"),+ (SeatType.FIRST, "recliner"),+ }+++class TestUnobservedSlots:+ """Slots the corpus never exercises must not drive a decoded value."""++ @pytest.mark.parametrize("slot", [2, 4, 6])+ def test_some_seats_power_slots_do_not_assert_power(self, slot):+ """Slots 2/4/6 occur zero times in 481 legs — report unknown.++ They are *reported* to be "some seats only" variants of 1/3/5,+ but nothing in the corpus backs that, so a leg whose first set+ power slot is one of them yields no power signal at all.+ """+ slots = [None] * 12+ slots[slot] = True+ amenities = _synthetic_leg(slots=slots).amenities+ assert amenities.power is None+ assert amenities.power_type is None+ assert amenities.usb_power is None++ def test_unknown_wifi_tier_still_reports_wifi(self):+ # Code 1 is reported to mean "Wi-Fi, tier unknown" but never+ # occurs; Wi-Fi is present either way, the tier is not guessed.+ slots = [None] * 12+ slots[11] = 1+ amenities = _synthetic_leg(slots=slots).amenities+ assert amenities.wifi is True+ assert amenities.wifi_tier is None++ def test_unknown_seat_quality_code_keeps_raw_rating(self):+ # Code 9 ("angled flat") is reported but unobserved.+ amenities = _synthetic_leg(slots=[None] * 12, seat_quality=9).amenities+ assert amenities.legroom_rating == 9+ assert amenities.seat_quality is None++ def test_first_set_power_slot_wins_even_when_unlabelled(self):+ """An unlabelled slot ahead of a labelled one yields unknown.++ Impossible per the corpus (the group is mutually exclusive), but+ Python and TypeScript must agree on it: both scan 1..6 in wire+ order and refuse to skip past a set slot they cannot name.+ """+ slots = [None] * 12+ slots[2] = True+ slots[3] = True+ amenities = _synthetic_leg(slots=slots).amenities+ assert amenities.power is None+ assert amenities.power_type is None+ assert amenities.usb_power is None+++class TestSlotValueTypes:+ """Only positive integers and ``true`` count as a set slot."""++ @pytest.mark.parametrize("flag", [True, 1])+ def test_boolean_and_integer_flags_both_count(self, flag):+ # The RPC payload uses JSON booleans, the public travel page uses 1.+ slots = [None] * 12+ slots[1] = flag+ assert _synthetic_leg(slots=slots).amenities.power_type == "plug_and_usb"++ @pytest.mark.parametrize("value", [False, 0, -1, 1.5, "1", None])+ def test_other_values_do_not_set_a_slot(self, value):+ slots = [None] * 12+ slots[1] = value+ assert _synthetic_leg(slots=slots).amenities.power is None++ @pytest.mark.parametrize("value", [2.5, "2", True])+ def test_non_integer_wifi_codes_are_ignored(self, value):+ slots = [None] * 12+ slots[11] = value+ amenities = _synthetic_leg(slots=slots).amenities+ assert amenities.wifi is None+ assert amenities.wifi_tier is None+++class TestLegroomInchesParsing:+ @pytest.mark.parametrize(+ ("text", "expected"),+ [+ ("31 in", 31),+ ("31 inches", 31),+ ("7 in", 7),+ # Non-ASCII digits satisfy str.isdigit() but are not seat+ # pitches; parsing them must not raise (a raised ValueError+ # in _parse_leg makes parse_flight_row drop the whole row).+ ("² in", None),+ ("١٢ in", None),+ ("", None),+ ("lie flat", None),+ ("0 in", None),+ ("-3 in", None),+ ],+ )+ def test_parses_only_plain_ascii_integers(self, text, expected):+ leg = _synthetic_leg(slots=[None] * 12, legroom=text)+ assert leg.amenities.legroom_inches == expected++ def test_unparseable_legroom_does_not_drop_the_row(self):+ """Regression: a superscript digit used to abort the whole row.++ ``"²".isdigit()`` is True but ``int("²")`` raises, and+ ``_parse_leg`` runs inside ``parse_flight_row``, so the raised+ ValueError would silently discard an otherwise-valid flight.+ """+ row = copy.deepcopy(_raw_rows("flight_search_jfk_lax_oneway_usd.bin")[0])+ row[0][2][0][14] = "² in"+ flight = parse_flight_row(row)+ assert flight.legs+ assert flight.legs[0].legroom_short == "² in"+ assert flight.legs[0].amenities.legroom_inches is None+++class TestCorpusInvariants:+ """Structural properties the decoder relies on, asserted on real data."""++ @staticmethod+ def _raw_legs(name: str):+ body = (FIXTURE_DIR / name).read_text()+ inner = json.loads(json.loads(body.lstrip(")]}'"))[0][2])+ rows = [item for i in (2, 3) if isinstance(inner[i], list) for item in inner[i][0]]+ for row in rows:+ yield from row[0][2] or []++ _FIXTURES = (+ "flight_search_jfk_lax_oneway_usd.bin",+ "flight_search_jfk_lax_eur.bin",+ "flight_search_jfk_lax_exclude_dl.bin",+ "flight_search_jfk_fra_oneworld.bin",+ "flight_search_buf_ath_min_layover_120.bin",+ "flight_search_lax_lhr_rt_biz_2a1c.bin",+ )++ @pytest.mark.parametrize("group", [range(1, 7), range(8, 11)])+ def test_slot_groups_are_mutually_exclusive(self, group):+ for name in self._FIXTURES:+ for fl in self._raw_legs(name):+ slots = fl[12]+ if not isinstance(slots, list):+ continue+ on = [i for i in group if i < len(slots) and slots[i]]+ assert len(on) <= 1, f"{name}: leg has multiple slots set in {group}: {on}"++ def test_wifi_slot_is_never_a_bool(self):+ """Slot 11 carries a tier code, so it must not be read as a flag."""+ for name in self._FIXTURES:+ for fl in self._raw_legs(name):+ slots = fl[12]+ if isinstance(slots, list) and len(slots) > 11 and slots[11] is not None:+ assert isinstance(slots[11], int) and not isinstance(slots[11], bool)diff --git a/tests/search/test_parse_flights_data.py b/tests/search/test_parse_flights_data.pyindex 67e9d9d..47d3e5d 100644--- a/tests/search/test_parse_flights_data.py+++ b/tests/search/test_parse_flights_data.py@@ -8,7 +8,7 @@ locking down the parser positions we depend on.import pytest-from fli.models import Airline, Airport+from fli.models import Airline, Airport, SeatTypefrom fli.search.flights import SearchFlights@@ -31,7 +31,11 @@ def _leg(dep_date=(2026, 7, 15),arr_date=(2026, 7, 15),co2=224716,- cabin=2,+ # leg[32] is an undecoded field that takes values 1/2/3 with no+ # relation to the cabin — economy legs in the captured fixtures carry+ # all three. The per-leg cabin lives at leg[16] (``cabin`` below).+ field_32=2,+ cabin=None,overnight=False,amenities=None,legroom_rating=None,@@ -48,6 +52,7 @@ def _leg(leg[12] = amenitiesleg[13] = legroom_ratingleg[14] = legroom_short+ leg[16] = cabinleg[17] = aircraftleg[19] = overnightleg[20] = list(dep_date)@@ -56,7 +61,7 @@ def _leg(leg[25] = 1leg[30] = legroom_longleg[31] = co2- leg[32] = cabin+ leg[32] = field_32return leg@@ -115,7 +120,10 @@ class TestParseFlightsDataNonStop:_leg(dep_iata="JFK",arr_iata="LAX",- amenities=[None, True, None, None, None, True, None, None, None, True, None, 2],+ # Slot 1 = AC-outlet-and-USB power, slot 9 = on-demand+ # seatback video, slot 11 = free Wi-Fi. Only one slot in+ # 1..6 and one in 8..10 is ever set on a real leg.+ amenities=[None, True, None, None, None, None, None, None, None, True, None, 2],legroom_rating=3,)],@@ -153,10 +161,13 @@ class TestParseFlightsDataNonStop:assert am.power is Trueassert am.on_demand_video is Trueassert am.legroom_rating == 3- # USB/in-seat-video slots not yet disambiguated — left as None to- # avoid lying about what we know.- assert am.usb_power is None- assert am.in_seat_video is None+ assert am.usb_power is True+ assert am.in_seat_video is True+ assert am.wifi_tier == "free"+ assert am.power_type == "plug_and_usb"+ assert am.video_type == "on_demand"+ assert am.seat_quality == "above_average"+ assert am.legroom_inches == 31def test_result_emissions(self):assert self.flight.co2_emissions_g == 225000@@ -175,6 +186,37 @@ class TestParseFlightsDataNonStop:assert self.flight.booking_token == "CAISA1VTRBoDCNR/sample"+class TestCabinCode:+ """``leg[16]`` decodes to SeatType; ``leg[32]`` is unrelated to it."""++ @pytest.mark.parametrize(+ ("code", "expected"),+ [+ (1, SeatType.ECONOMY),+ (2, SeatType.PREMIUM_ECONOMY),+ (3, SeatType.BUSINESS),+ (4, SeatType.FIRST),+ ],+ )+ def test_decodes_each_cabin_code(self, code, expected):+ row = _row(legs=[_leg(dep_iata="JFK", arr_iata="LAX", cabin=code)])+ assert SearchFlights._parse_flights_data(row).legs[0].cabin is expected++ @pytest.mark.parametrize("code", [None, 0, 5, 99, -1, True, "3", 2.0])+ def test_absent_or_unknown_codes_give_none(self, code):+ row = _row(legs=[_leg(dep_iata="JFK", arr_iata="LAX", cabin=code)])+ assert SearchFlights._parse_flights_data(row).legs[0].cabin is None++ def test_field_32_is_not_the_cabin(self):+ """leg[32] must not leak into ``cabin``.++ It holds 1/2/3 on economy legs throughout the captured fixtures,+ so reading it as a cabin code would mislabel most of the corpus.+ """+ row = _row(legs=[_leg(dep_iata="JFK", arr_iata="LAX", field_32=3, cabin=None)])+ assert SearchFlights._parse_flights_data(row).legs[0].cabin is None++class TestLegroomRating:@pytest.mark.parametrize("rating", range(1, 10))@pytest.mark.parametrize("wifi_tier", [2, 3])