{
 "edition": "coding-models/2026-11",
 "tasks": [
  {
   "id": "01-invoice-vat",
   "title": "Invoice VAT rounding",
   "difficulty": "easy",
   "bugKind": "decimal rounding mode",
   "description": "This module computes invoice totals from lines with a unit price, quantity and VAT percentage. line_vat returns the VAT of a single line rounded half-up to whole cents, and invoice_total returns a dict with the summed net, vat and gross amounts. All amounts are Decimal values.",
   "buggy.py": "\"\"\"Invoice totals with per-line VAT rounding.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\n@dataclass(frozen=True)\nclass Line:\n    \"\"\"One invoice line: unit price, quantity and VAT rate in percent.\"\"\"\n\n    unit_price: Decimal\n    quantity: int\n    vat_percent: Decimal\n\n\ndef line_net(line: Line) -> Decimal:\n    \"\"\"Net amount of a line, rounded to cents.\"\"\"\n    return (line.unit_price * line.quantity).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef line_vat(line: Line) -> Decimal:\n    \"\"\"VAT for one line, rounded half-up to cents.\"\"\"\n    raw = line_net(line) * line.vat_percent / Decimal(100)\n    return raw.quantize(CENT, rounding=\"ROUND_HALF_EVEN\")\n\n\ndef invoice_total(lines: list[Line]) -> dict[str, Decimal]:\n    \"\"\"Return net, vat and gross totals for the invoice.\"\"\"\n    net = sum((line_net(item) for item in lines), Decimal(\"0.00\"))\n    vat = sum((line_vat(item) for item in lines), Decimal(\"0.00\"))\n    return {\"net\": net, \"vat\": vat, \"gross\": net + vat}\n",
   "test_visible.py": "import unittest\nfrom decimal import Decimal\nfrom solution import Line, line_vat\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_half_cent_rounds_up(self):\n        line = Line(Decimal(\"0.10\"), 1, Decimal(\"5\"))\n        self.assertEqual(line_vat(line), Decimal(\"0.01\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom decimal import Decimal as D\nfrom solution import Line, line_net, line_vat, invoice_total\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_exact_vat(self):\n        self.assertEqual(line_vat(Line(D(\"10.00\"), 2, D(\"20\"))), D(\"4.00\"))\n\n    def test_half_cent_up_small(self):\n        self.assertEqual(line_vat(Line(D(\"0.10\"), 1, D(\"5\"))), D(\"0.01\"))\n\n    def test_half_cent_up_even_neighbour(self):\n        self.assertEqual(line_vat(Line(D(\"0.50\"), 1, D(\"5\"))), D(\"0.03\"))\n\n    def test_half_cent_up_larger(self):\n        self.assertEqual(line_vat(Line(D(\"10.50\"), 1, D(\"5\"))), D(\"0.53\"))\n\n    def test_below_half_rounds_down(self):\n        self.assertEqual(line_vat(Line(D(\"19.99\"), 3, D(\"23\"))), D(\"13.79\"))\n\n    def test_net_rounding(self):\n        self.assertEqual(line_net(Line(D(\"1.005\"), 1, D(\"0\"))), D(\"1.01\"))\n\n    def test_zero_rate(self):\n        self.assertEqual(line_vat(Line(D(\"9.99\"), 4, D(\"0\"))), D(\"0.00\"))\n\n    def test_total_sums_rounded_lines(self):\n        lines = [Line(D(\"0.10\"), 1, D(\"5\")), Line(D(\"0.10\"), 1, D(\"5\"))]\n        t = invoice_total(lines)\n        self.assertEqual(t[\"vat\"], D(\"0.02\"))\n        self.assertEqual(t[\"net\"], D(\"0.20\"))\n        self.assertEqual(t[\"gross\"], D(\"0.22\"))\n\n    def test_empty_invoice(self):\n        t = invoice_total([])\n        self.assertEqual(t, {\"net\": D(\"0.00\"), \"vat\": D(\"0.00\"), \"gross\": D(\"0.00\")})\n\n    def test_mixed_rates(self):\n        lines = [Line(D(\"12.50\"), 2, D(\"23\")), Line(D(\"3.30\"), 1, D(\"8\"))]\n        t = invoice_total(lines)\n        self.assertEqual(t[\"net\"], D(\"28.30\"))\n        self.assertEqual(t[\"vat\"], D(\"5.75\") + D(\"0.26\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Invoice totals with per-line VAT rounding.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\n@dataclass(frozen=True)\nclass Line:\n    \"\"\"One invoice line: unit price, quantity and VAT rate in percent.\"\"\"\n\n    unit_price: Decimal\n    quantity: int\n    vat_percent: Decimal\n\n\ndef line_net(line: Line) -> Decimal:\n    \"\"\"Net amount of a line, rounded to cents.\"\"\"\n    return (line.unit_price * line.quantity).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef line_vat(line: Line) -> Decimal:\n    \"\"\"VAT for one line, rounded half-up to cents.\"\"\"\n    raw = line_net(line) * line.vat_percent / Decimal(100)\n    return raw.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef invoice_total(lines: list[Line]) -> dict[str, Decimal]:\n    \"\"\"Return net, vat and gross totals for the invoice.\"\"\"\n    net = sum((line_net(item) for item in lines), Decimal(\"0.00\"))\n    vat = sum((line_vat(item) for item in lines), Decimal(\"0.00\"))\n    return {\"net\": net, \"vat\": vat, \"gross\": net + vat}\n"
  },
  {
   "id": "02-slugify",
   "title": "Title slugs with stopwords",
   "difficulty": "easy",
   "bugKind": "case sensitivity",
   "description": "This module builds URL slugs from article titles. slugify lowercases the title, drops stopwords (matched ignoring case, the stopword set is given in lowercase) and joins the remaining words with hyphens. unique_slug appends -2, -3 and so on until the slug is not already taken.",
   "buggy.py": "\"\"\"Turn article titles into URL slugs.\"\"\"\nfrom __future__ import annotations\n\nimport re\n\nDEFAULT_STOPWORDS = frozenset({\"a\", \"an\", \"the\", \"of\", \"and\", \"to\", \"in\"})\n\n\ndef _words(title: str) -> list[str]:\n    \"\"\"Split a title into alphanumeric words.\"\"\"\n    return re.findall(r\"[A-Za-z0-9]+\", title)\n\n\ndef slugify(title: str, stopwords: frozenset[str] = DEFAULT_STOPWORDS,\n            max_words: int | None = None) -> str:\n    \"\"\"Lowercase, hyphen-joined slug without stopwords.\n\n    Stopwords are matched case-insensitively. If every word is a stopword the\n    words are kept as they are. ``max_words`` limits the number of words.\n    \"\"\"\n    words = _words(title)\n    kept = [w for w in words if w not in stopwords]\n    if not kept:\n        kept = words\n    if max_words is not None:\n        kept = kept[:max_words]\n    return \"-\".join(w.lower() for w in kept)\n\n\ndef unique_slug(title: str, existing: set[str]) -> str:\n    \"\"\"Slugify and append -2, -3 ... until the slug is not in ``existing``.\"\"\"\n    base = slugify(title)\n    slug = base\n    n = 2\n    while slug in existing:\n        slug = f\"{base}-{n}\"\n        n += 1\n    return slug\n",
   "test_visible.py": "import unittest\nfrom solution import slugify\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_capitalised_stopword_removed(self):\n        self.assertEqual(slugify(\"The Art of War\"), \"art-war\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import slugify, unique_slug\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_basic(self):\n        self.assertEqual(slugify(\"Hello World\"), \"hello-world\")\n\n    def test_mixed_case_stopwords(self):\n        self.assertEqual(slugify(\"The Lord OF The Rings\"), \"lord-rings\")\n\n    def test_upper_case_stopword(self):\n        self.assertEqual(slugify(\"AND Then There Were None\"), \"then-there-were-none\")\n\n    def test_punctuation(self):\n        self.assertEqual(slugify(\"Hello, World! It's 2024\"), \"hello-world-it-s-2024\")\n\n    def test_max_words(self):\n        self.assertEqual(slugify(\"one two three four\", max_words=2), \"one-two\")\n\n    def test_all_stopwords_kept(self):\n        self.assertEqual(slugify(\"The And\"), \"the-and\")\n\n    def test_custom_stopwords(self):\n        self.assertEqual(slugify(\"Foo Bar\", frozenset({\"foo\"})), \"bar\")\n\n    def test_extra_whitespace(self):\n        self.assertEqual(slugify(\"  a   Big   Day \"), \"big-day\")\n\n    def test_unique_free(self):\n        self.assertEqual(unique_slug(\"My Post\", set()), \"my-post\")\n\n    def test_unique_taken(self):\n        self.assertEqual(unique_slug(\"My Post\", {\"my-post\", \"my-post-2\"}), \"my-post-3\")\n\n    def test_unique_uses_normalised_stopwords(self):\n        self.assertEqual(unique_slug(\"The Post\", {\"post\"}), \"post-2\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Turn article titles into URL slugs.\"\"\"\nfrom __future__ import annotations\n\nimport re\n\nDEFAULT_STOPWORDS = frozenset({\"a\", \"an\", \"the\", \"of\", \"and\", \"to\", \"in\"})\n\n\ndef _words(title: str) -> list[str]:\n    \"\"\"Split a title into alphanumeric words.\"\"\"\n    return re.findall(r\"[A-Za-z0-9]+\", title)\n\n\ndef slugify(title: str, stopwords: frozenset[str] = DEFAULT_STOPWORDS,\n            max_words: int | None = None) -> str:\n    \"\"\"Lowercase, hyphen-joined slug without stopwords.\n\n    Stopwords are matched case-insensitively. If every word is a stopword the\n    words are kept as they are. ``max_words`` limits the number of words.\n    \"\"\"\n    words = _words(title)\n    kept = [w for w in words if w.lower() not in stopwords]\n    if not kept:\n        kept = words\n    if max_words is not None:\n        kept = kept[:max_words]\n    return \"-\".join(w.lower() for w in kept)\n\n\ndef unique_slug(title: str, existing: set[str]) -> str:\n    \"\"\"Slugify and append -2, -3 ... until the slug is not in ``existing``.\"\"\"\n    base = slugify(title)\n    slug = base\n    n = 2\n    while slug in existing:\n        slug = f\"{base}-{n}\"\n        n += 1\n    return slug\n"
  },
  {
   "id": "03-pagination",
   "title": "1-based pagination",
   "difficulty": "easy",
   "bugKind": "off-by-one in slice start",
   "description": "This module paginates sequences using 1-based page numbers. page_count gives the number of pages for a given total and page size (at least 1, even when empty), and paginate returns a Page holding the items of the requested page plus its number and the total page count. Page numbers outside the valid range raise ValueError.",
   "buggy.py": "\"\"\"Simple 1-based pagination helpers.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Sequence, TypeVar\n\nT = TypeVar(\"T\")\n\n\n@dataclass(frozen=True)\nclass Page:\n    \"\"\"A page of items plus navigation info.\"\"\"\n\n    items: list\n    number: int\n    total_pages: int\n\n    @property\n    def has_next(self) -> bool:\n        \"\"\"True when a later page exists.\"\"\"\n        return self.number < self.total_pages\n\n    @property\n    def has_prev(self) -> bool:\n        \"\"\"True when an earlier page exists.\"\"\"\n        return self.number > 1\n\n\ndef page_count(total: int, size: int) -> int:\n    \"\"\"Number of pages needed for ``total`` items; at least 1.\"\"\"\n    if size < 1:\n        raise ValueError(\"size must be positive\")\n    return max(1, -(-total // size))\n\n\ndef paginate(items: Sequence[T], number: int, size: int) -> Page:\n    \"\"\"Return page ``number`` (1-based). Out-of-range numbers raise ValueError.\"\"\"\n    pages = page_count(len(items), size)\n    if not 1 <= number <= pages:\n        raise ValueError(\"page out of range\")\n    start = number * size\n    return Page(list(items[start:start + size]), number, pages)\n",
   "test_visible.py": "import unittest\nfrom solution import paginate\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_first_page_has_first_items(self):\n        page = paginate(list(range(1, 11)), 1, 3)\n        self.assertEqual(page.items, [1, 2, 3])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import paginate, page_count\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_second_page(self):\n        self.assertEqual(paginate(list(range(1, 11)), 2, 3).items, [4, 5, 6])\n\n    def test_last_partial_page(self):\n        page = paginate(list(range(1, 11)), 4, 3)\n        self.assertEqual(page.items, [10])\n        self.assertEqual(page.total_pages, 4)\n\n    def test_exact_multiple(self):\n        self.assertEqual(page_count(9, 3), 3)\n        self.assertEqual(paginate(list(range(9)), 3, 3).items, [6, 7, 8])\n\n    def test_empty_has_one_page(self):\n        page = paginate([], 1, 5)\n        self.assertEqual(page.items, [])\n        self.assertEqual(page.total_pages, 1)\n        self.assertFalse(page.has_next)\n\n    def test_out_of_range(self):\n        data = list(range(5))\n        with self.assertRaises(ValueError):\n            paginate(data, 0, 2)\n        with self.assertRaises(ValueError):\n            paginate(data, 4, 2)\n\n    def test_navigation_flags(self):\n        data = list(range(7))\n        self.assertTrue(paginate(data, 1, 3).has_next)\n        self.assertFalse(paginate(data, 1, 3).has_prev)\n        self.assertTrue(paginate(data, 2, 3).has_prev)\n        self.assertFalse(paginate(data, 3, 3).has_next)\n\n    def test_bad_size(self):\n        with self.assertRaises(ValueError):\n            paginate([1], 1, 0)\n\n    def test_tuple_input_and_number(self):\n        page = paginate((\"a\", \"b\", \"c\"), 2, 2)\n        self.assertEqual(page.items, [\"c\"])\n        self.assertEqual(page.number, 2)\n\n    def test_page_count_values(self):\n        self.assertEqual(page_count(0, 10), 1)\n        self.assertEqual(page_count(1, 10), 1)\n        self.assertEqual(page_count(11, 10), 2)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Simple 1-based pagination helpers.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Sequence, TypeVar\n\nT = TypeVar(\"T\")\n\n\n@dataclass(frozen=True)\nclass Page:\n    \"\"\"A page of items plus navigation info.\"\"\"\n\n    items: list\n    number: int\n    total_pages: int\n\n    @property\n    def has_next(self) -> bool:\n        \"\"\"True when a later page exists.\"\"\"\n        return self.number < self.total_pages\n\n    @property\n    def has_prev(self) -> bool:\n        \"\"\"True when an earlier page exists.\"\"\"\n        return self.number > 1\n\n\ndef page_count(total: int, size: int) -> int:\n    \"\"\"Number of pages needed for ``total`` items; at least 1.\"\"\"\n    if size < 1:\n        raise ValueError(\"size must be positive\")\n    return max(1, -(-total // size))\n\n\ndef paginate(items: Sequence[T], number: int, size: int) -> Page:\n    \"\"\"Return page ``number`` (1-based). Out-of-range numbers raise ValueError.\"\"\"\n    pages = page_count(len(items), size)\n    if not 1 <= number <= pages:\n        raise ValueError(\"page out of range\")\n    start = (number - 1) * size\n    return Page(list(items[start:start + size]), number, pages)\n"
  },
  {
   "id": "04-shipping-cost",
   "title": "Shipping tiers and zones",
   "difficulty": "medium",
   "bugKind": "wrong default in dict.get",
   "description": "This module prices parcels by weight tier and destination zone. shipping_cost returns the base price of the first tier that fits the weight, doubled for express shipments, plus the surcharge for the zone. Destinations that are not a known zone are charged like the 'other' zone. Non-positive weights and parcels over the heaviest tier raise ValueError.",
   "buggy.py": "\"\"\"Shipping cost calculation from weight tiers and destination zone.\"\"\"\nfrom __future__ import annotations\n\nfrom decimal import Decimal\n\n# (max weight in kg, inclusive; price)\nTIERS = [\n    (Decimal(\"1\"), Decimal(\"4.90\")),\n    (Decimal(\"5\"), Decimal(\"7.90\")),\n    (Decimal(\"20\"), Decimal(\"12.90\")),\n]\nZONE_SURCHARGE = {\n    \"domestic\": Decimal(\"0.00\"),\n    \"eu\": Decimal(\"3.00\"),\n    \"other\": Decimal(\"9.50\"),\n}\nMAX_WEIGHT = TIERS[-1][0]\n\n\ndef base_price(weight_kg: Decimal) -> Decimal:\n    \"\"\"Price of the first tier whose limit is >= weight.\"\"\"\n    if weight_kg <= 0:\n        raise ValueError(\"weight must be positive\")\n    for limit, price in TIERS:\n        if weight_kg <= limit:\n            return price\n    raise ValueError(\"parcel too heavy\")\n\n\ndef shipping_cost(weight_kg: Decimal, zone: str, express: bool = False) -> Decimal:\n    \"\"\"Total shipping cost.\n\n    Unknown zones are charged like the ``other`` zone. Express doubles the\n    base price but not the zone surcharge.\n    \"\"\"\n    base = base_price(weight_kg)\n    if express:\n        base *= 2\n    surcharge = ZONE_SURCHARGE.get(zone, Decimal(\"0.00\"))\n    return base + surcharge\n",
   "test_visible.py": "import unittest\nfrom decimal import Decimal\nfrom solution import shipping_cost\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_unknown_zone(self):\n        self.assertEqual(shipping_cost(Decimal(\"2\"), \"mars\"), Decimal(\"17.40\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom decimal import Decimal as D\nfrom solution import shipping_cost, base_price\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_tier_limits_inclusive(self):\n        self.assertEqual(base_price(D(\"1\")), D(\"4.90\"))\n        self.assertEqual(base_price(D(\"5\")), D(\"7.90\"))\n        self.assertEqual(base_price(D(\"20\")), D(\"12.90\"))\n\n    def test_just_over_limit(self):\n        self.assertEqual(base_price(D(\"1.01\")), D(\"7.90\"))\n        self.assertEqual(base_price(D(\"5.5\")), D(\"12.90\"))\n\n    def test_light_parcel(self):\n        self.assertEqual(base_price(D(\"0.2\")), D(\"4.90\"))\n\n    def test_too_heavy(self):\n        with self.assertRaises(ValueError):\n            base_price(D(\"20.01\"))\n\n    def test_non_positive(self):\n        with self.assertRaises(ValueError):\n            base_price(D(\"0\"))\n        with self.assertRaises(ValueError):\n            base_price(D(\"-1\"))\n\n    def test_domestic(self):\n        self.assertEqual(shipping_cost(D(\"3\"), \"domestic\"), D(\"7.90\"))\n\n    def test_eu(self):\n        self.assertEqual(shipping_cost(D(\"3\"), \"eu\"), D(\"10.90\"))\n\n    def test_other_known(self):\n        self.assertEqual(shipping_cost(D(\"3\"), \"other\"), D(\"17.40\"))\n\n    def test_unknown_zone_like_other(self):\n        self.assertEqual(shipping_cost(D(\"0.5\"), \"narnia\"), D(\"14.40\"))\n        self.assertEqual(shipping_cost(D(\"0.5\"), \"\"), D(\"14.40\"))\n\n    def test_zone_name_is_exact(self):\n        self.assertEqual(shipping_cost(D(\"1\"), \"EU\"), D(\"14.40\"))\n\n    def test_express_doubles_base_only(self):\n        self.assertEqual(shipping_cost(D(\"3\"), \"eu\", express=True), D(\"18.80\"))\n        self.assertEqual(shipping_cost(D(\"3\"), \"xx\", express=True), D(\"25.30\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Shipping cost calculation from weight tiers and destination zone.\"\"\"\nfrom __future__ import annotations\n\nfrom decimal import Decimal\n\n# (max weight in kg, inclusive; price)\nTIERS = [\n    (Decimal(\"1\"), Decimal(\"4.90\")),\n    (Decimal(\"5\"), Decimal(\"7.90\")),\n    (Decimal(\"20\"), Decimal(\"12.90\")),\n]\nZONE_SURCHARGE = {\n    \"domestic\": Decimal(\"0.00\"),\n    \"eu\": Decimal(\"3.00\"),\n    \"other\": Decimal(\"9.50\"),\n}\nMAX_WEIGHT = TIERS[-1][0]\n\n\ndef base_price(weight_kg: Decimal) -> Decimal:\n    \"\"\"Price of the first tier whose limit is >= weight.\"\"\"\n    if weight_kg <= 0:\n        raise ValueError(\"weight must be positive\")\n    for limit, price in TIERS:\n        if weight_kg <= limit:\n            return price\n    raise ValueError(\"parcel too heavy\")\n\n\ndef shipping_cost(weight_kg: Decimal, zone: str, express: bool = False) -> Decimal:\n    \"\"\"Total shipping cost.\n\n    Unknown zones are charged like the ``other`` zone. Express doubles the\n    base price but not the zone surcharge.\n    \"\"\"\n    base = base_price(weight_kg)\n    if express:\n        base *= 2\n    surcharge = ZONE_SURCHARGE.get(zone, ZONE_SURCHARGE[\"other\"])\n    return base + surcharge\n"
  },
  {
   "id": "05-leaderboard",
   "title": "Leaderboard with ties",
   "difficulty": "medium",
   "bugKind": "wrong sort key / reverse flag",
   "description": "This module ranks players on a leaderboard. sort_scores orders players by score from highest to lowest, with equal scores ordered by name A to Z. ranked returns (rank, name, score) rows using competition ranking, so equal scores share a rank and the next rank is skipped (1, 2, 2, 4). top returns the names whose rank is at most n, which can be more than n when there are ties.",
   "buggy.py": "\"\"\"Leaderboard ranking with competition-style ties (1, 2, 2, 4).\"\"\"\nfrom __future__ import annotations\n\n\ndef sort_scores(scores: dict[str, int]) -> list[tuple[str, int]]:\n    \"\"\"Players ordered by score (highest first), ties by name A-Z.\"\"\"\n    return sorted(scores.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)\n\n\ndef ranked(scores: dict[str, int]) -> list[tuple[int, str, int]]:\n    \"\"\"(rank, name, score) rows; equal scores share the lowest rank number.\"\"\"\n    rows: list[tuple[int, str, int]] = []\n    previous: int | None = None\n    rank = 0\n    for position, (name, score) in enumerate(sort_scores(scores), start=1):\n        if score != previous:\n            rank = position\n            previous = score\n        rows.append((rank, name, score))\n    return rows\n\n\ndef top(scores: dict[str, int], n: int) -> list[str]:\n    \"\"\"Names of players whose rank is <= n (more than n on ties).\"\"\"\n    return [name for rank, name, _ in ranked(scores) if rank <= n]\n\n\ndef rank_of(scores: dict[str, int], name: str) -> int:\n    \"\"\"Rank of one player; raises KeyError for unknown names.\"\"\"\n    if name not in scores:\n        raise KeyError(name)\n    for rank, player, _ in ranked(scores):\n        if player == name:\n            return rank\n    raise KeyError(name)\n",
   "test_visible.py": "import unittest\nfrom solution import sort_scores\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_ties_sorted_by_name(self):\n        scores = {\"bob\": 5, \"amy\": 5, \"cy\": 9}\n        self.assertEqual(sort_scores(scores), [(\"cy\", 9), (\"amy\", 5), (\"bob\", 5)])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import sort_scores, ranked, top, rank_of\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_sort_distinct(self):\n        self.assertEqual(sort_scores({\"a\": 1, \"b\": 3, \"c\": 2}), [(\"b\", 3), (\"c\", 2), (\"a\", 1)])\n\n    def test_sort_ties_alphabetical(self):\n        scores = {\"zed\": 4, \"amy\": 4, \"mid\": 4}\n        self.assertEqual([n for n, _ in sort_scores(scores)], [\"amy\", \"mid\", \"zed\"])\n\n    def test_sort_negative_and_zero(self):\n        self.assertEqual(sort_scores({\"a\": -1, \"b\": 0, \"c\": -1}), [(\"b\", 0), (\"a\", -1), (\"c\", -1)])\n\n    def test_competition_ranking(self):\n        scores = {\"a\": 10, \"b\": 8, \"c\": 8, \"d\": 5}\n        self.assertEqual([r for r, _, _ in ranked(scores)], [1, 2, 2, 4])\n\n    def test_ranked_rows(self):\n        self.assertEqual(ranked({\"b\": 2, \"a\": 2}), [(1, \"a\", 2), (1, \"b\", 2)])\n\n    def test_all_equal(self):\n        self.assertEqual([r for r, _, _ in ranked({\"x\": 1, \"y\": 1, \"z\": 1})], [1, 1, 1])\n\n    def test_empty(self):\n        self.assertEqual(sort_scores({}), [])\n        self.assertEqual(ranked({}), [])\n        self.assertEqual(top({}, 3), [])\n\n    def test_top_with_ties(self):\n        scores = {\"a\": 10, \"b\": 8, \"c\": 8, \"d\": 5}\n        self.assertEqual(top(scores, 2), [\"a\", \"b\", \"c\"])\n        self.assertEqual(top(scores, 1), [\"a\"])\n\n    def test_rank_of(self):\n        scores = {\"a\": 10, \"b\": 8, \"c\": 8, \"d\": 5}\n        self.assertEqual(rank_of(scores, \"c\"), 2)\n        self.assertEqual(rank_of(scores, \"d\"), 4)\n        with self.assertRaises(KeyError):\n            rank_of(scores, \"nobody\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Leaderboard ranking with competition-style ties (1, 2, 2, 4).\"\"\"\nfrom __future__ import annotations\n\n\ndef sort_scores(scores: dict[str, int]) -> list[tuple[str, int]]:\n    \"\"\"Players ordered by score (highest first), ties by name A-Z.\"\"\"\n    return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))\n\n\ndef ranked(scores: dict[str, int]) -> list[tuple[int, str, int]]:\n    \"\"\"(rank, name, score) rows; equal scores share the lowest rank number.\"\"\"\n    rows: list[tuple[int, str, int]] = []\n    previous: int | None = None\n    rank = 0\n    for position, (name, score) in enumerate(sort_scores(scores), start=1):\n        if score != previous:\n            rank = position\n            previous = score\n        rows.append((rank, name, score))\n    return rows\n\n\ndef top(scores: dict[str, int], n: int) -> list[str]:\n    \"\"\"Names of players whose rank is <= n (more than n on ties).\"\"\"\n    return [name for rank, name, _ in ranked(scores) if rank <= n]\n\n\ndef rank_of(scores: dict[str, int], name: str) -> int:\n    \"\"\"Rank of one player; raises KeyError for unknown names.\"\"\"\n    if name not in scores:\n        raise KeyError(name)\n    for rank, player, _ in ranked(scores):\n        if player == name:\n            return rank\n    raise KeyError(name)\n"
  },
  {
   "id": "06-ticket-tags",
   "title": "Ticket tag collector",
   "difficulty": "easy",
   "bugKind": "mutable default argument",
   "description": "This module collects normalized tags for support tickets. normalize_tag trims, lowercases and replaces inner whitespace with hyphens. add_tags appends the normalized new tags to a tag list, skipping duplicates and keeping first-seen order, and returns that list. When no list is passed in it starts from a fresh empty list on every call.",
   "buggy.py": "\"\"\"Collect tags for support tickets.\"\"\"\nfrom __future__ import annotations\n\nimport re\nfrom typing import Iterable\n\n\ndef normalize_tag(raw: str) -> str:\n    \"\"\"Trim, lowercase and hyphenate a tag; empty results are rejected.\"\"\"\n    tag = re.sub(r\"\\s+\", \"-\", raw.strip().lower())\n    if not tag:\n        raise ValueError(\"empty tag\")\n    return tag\n\n\ndef add_tags(new_tags: Iterable[str], tags: list[str] = []) -> list[str]:\n    \"\"\"Append normalized ``new_tags`` to ``tags`` without duplicates.\n\n    Returns the list that was passed in (extended in place), or a new list\n    when none is given.\n    \"\"\"\n    for raw in new_tags:\n        tag = normalize_tag(raw)\n        if tag not in tags:\n            tags.append(tag)\n    return tags\n\n\ndef merge_tag_sets(*groups: Iterable[str]) -> list[str]:\n    \"\"\"Union of several tag groups in first-seen order.\"\"\"\n    merged: list[str] = []\n    for group in groups:\n        add_tags(group, merged)\n    return merged\n\n\ndef has_tag(tags: Iterable[str], wanted: str) -> bool:\n    \"\"\"True if ``wanted`` (after normalization) is among ``tags``.\"\"\"\n    return normalize_tag(wanted) in set(tags)\n",
   "test_visible.py": "import unittest\nfrom solution import add_tags\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_calls_do_not_share_state(self):\n        add_tags([\"Bug\"])\n        self.assertEqual(add_tags([\"Urgent\"]), [\"urgent\"])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import add_tags, normalize_tag, merge_tag_sets, has_tag\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_normalize(self):\n        self.assertEqual(normalize_tag(\"  Needs   Review \"), \"needs-review\")\n\n    def test_normalize_empty(self):\n        with self.assertRaises(ValueError):\n            normalize_tag(\"   \")\n\n    def test_fresh_list_each_call(self):\n        first = add_tags([\"a\"])\n        second = add_tags([\"b\"])\n        self.assertEqual(first, [\"a\"])\n        self.assertEqual(second, [\"b\"])\n        self.assertIsNot(first, second)\n\n    def test_three_calls_independent(self):\n        add_tags([\"x\"])\n        add_tags([\"y\"])\n        self.assertEqual(add_tags([]), [])\n\n    def test_duplicates_skipped(self):\n        self.assertEqual(add_tags([\"A\", \"a\", \" A \"]), [\"a\"])\n\n    def test_order_kept(self):\n        self.assertEqual(add_tags([\"b\", \"a\", \"c\", \"a\"]), [\"b\", \"a\", \"c\"])\n\n    def test_passed_list_extended_in_place(self):\n        mine = [\"x\"]\n        result = add_tags([\"y\", \"x\"], mine)\n        self.assertIs(result, mine)\n        self.assertEqual(mine, [\"x\", \"y\"])\n\n    def test_merge_sets(self):\n        self.assertEqual(merge_tag_sets([\"a\", \"b\"], [\"B\", \"c\"], []), [\"a\", \"b\", \"c\"])\n\n    def test_merge_does_not_leak(self):\n        merge_tag_sets([\"a\"])\n        self.assertEqual(merge_tag_sets([\"z\"]), [\"z\"])\n\n    def test_has_tag(self):\n        self.assertTrue(has_tag([\"urgent\"], \" URGENT\"))\n        self.assertFalse(has_tag([\"urgent\"], \"later\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Collect tags for support tickets.\"\"\"\nfrom __future__ import annotations\n\nimport re\nfrom typing import Iterable\n\n\ndef normalize_tag(raw: str) -> str:\n    \"\"\"Trim, lowercase and hyphenate a tag; empty results are rejected.\"\"\"\n    tag = re.sub(r\"\\s+\", \"-\", raw.strip().lower())\n    if not tag:\n        raise ValueError(\"empty tag\")\n    return tag\n\n\ndef add_tags(new_tags: Iterable[str], tags: list[str] | None = None) -> list[str]:\n    \"\"\"Append normalized ``new_tags`` to ``tags`` without duplicates.\n\n    Returns the list that was passed in (extended in place), or a new list\n    when none is given.\n    \"\"\"\n    if tags is None:\n        tags = []\n    for raw in new_tags:\n        tag = normalize_tag(raw)\n        if tag not in tags:\n            tags.append(tag)\n    return tags\n\n\ndef merge_tag_sets(*groups: Iterable[str]) -> list[str]:\n    \"\"\"Union of several tag groups in first-seen order.\"\"\"\n    merged: list[str] = []\n    for group in groups:\n        add_tags(group, merged)\n    return merged\n\n\ndef has_tag(tags: Iterable[str], wanted: str) -> bool:\n    \"\"\"True if ``wanted`` (after normalization) is among ``tags``.\"\"\"\n    return normalize_tag(wanted) in set(tags)\n"
  },
  {
   "id": "07-latency-stats",
   "title": "Response time statistics",
   "difficulty": "easy",
   "bugKind": "integer vs true division",
   "description": "This module summarizes response times in milliseconds for a monitoring page. mean_ms returns the arithmetic mean as a float (0.0 for no samples), over_budget_ratio returns the fraction of samples strictly above a budget (0.0 for no samples), and slowest returns the n largest samples in descending order.",
   "buggy.py": "\"\"\"Response-time statistics for a monitoring dashboard.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Sequence\n\n\ndef mean_ms(samples: Sequence[int]) -> float:\n    \"\"\"Arithmetic mean of the samples; 0.0 when there are none.\"\"\"\n    if not samples:\n        return 0.0\n    return sum(samples) // len(samples)\n\n\ndef over_budget_ratio(samples: Sequence[int], budget_ms: int) -> float:\n    \"\"\"Fraction of samples strictly slower than ``budget_ms``.\"\"\"\n    if not samples:\n        return 0.0\n    slow = sum(1 for s in samples if s > budget_ms)\n    return slow / len(samples)\n\n\ndef slowest(samples: Sequence[int], n: int) -> list[int]:\n    \"\"\"The ``n`` largest samples, biggest first.\"\"\"\n    if n < 0:\n        raise ValueError(\"n must not be negative\")\n    return sorted(samples, reverse=True)[:n]\n\n\ndef summary(samples: Sequence[int], budget_ms: int) -> dict[str, float]:\n    \"\"\"Mean, worst sample and over-budget ratio in one dict.\"\"\"\n    return {\n        \"mean\": mean_ms(samples),\n        \"worst\": float(max(samples)) if samples else 0.0,\n        \"over_budget\": over_budget_ratio(samples, budget_ms),\n    }\n",
   "test_visible.py": "import unittest\nfrom solution import mean_ms\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_fractional_mean(self):\n        self.assertEqual(mean_ms([100, 101]), 100.5)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import mean_ms, over_budget_ratio, slowest, summary\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_mean_whole(self):\n        self.assertEqual(mean_ms([10, 20, 30]), 20.0)\n\n    def test_mean_fraction(self):\n        self.assertAlmostEqual(mean_ms([1, 2, 2]), 5 / 3)\n\n    def test_mean_half(self):\n        self.assertEqual(mean_ms([1, 2]), 1.5)\n\n    def test_mean_single_and_empty(self):\n        self.assertEqual(mean_ms([7]), 7.0)\n        self.assertEqual(mean_ms([]), 0.0)\n\n    def test_mean_is_float(self):\n        self.assertIsInstance(mean_ms([4, 4]), float)\n\n    def test_ratio(self):\n        self.assertEqual(over_budget_ratio([100, 200, 300, 400], 250), 0.5)\n\n    def test_ratio_strict(self):\n        self.assertEqual(over_budget_ratio([100, 200], 200), 0.0)\n\n    def test_ratio_empty(self):\n        self.assertEqual(over_budget_ratio([], 10), 0.0)\n\n    def test_slowest(self):\n        self.assertEqual(slowest([5, 1, 9, 7], 2), [9, 7])\n        self.assertEqual(slowest([5, 1], 5), [5, 1])\n        self.assertEqual(slowest([5, 1], 0), [])\n\n    def test_slowest_negative(self):\n        with self.assertRaises(ValueError):\n            slowest([1], -1)\n\n    def test_summary(self):\n        s = summary([100, 201], 150)\n        self.assertEqual(s[\"mean\"], 150.5)\n        self.assertEqual(s[\"worst\"], 201.0)\n        self.assertEqual(s[\"over_budget\"], 0.5)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Response-time statistics for a monitoring dashboard.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Sequence\n\n\ndef mean_ms(samples: Sequence[int]) -> float:\n    \"\"\"Arithmetic mean of the samples; 0.0 when there are none.\"\"\"\n    if not samples:\n        return 0.0\n    return sum(samples) / len(samples)\n\n\ndef over_budget_ratio(samples: Sequence[int], budget_ms: int) -> float:\n    \"\"\"Fraction of samples strictly slower than ``budget_ms``.\"\"\"\n    if not samples:\n        return 0.0\n    slow = sum(1 for s in samples if s > budget_ms)\n    return slow / len(samples)\n\n\ndef slowest(samples: Sequence[int], n: int) -> list[int]:\n    \"\"\"The ``n`` largest samples, biggest first.\"\"\"\n    if n < 0:\n        raise ValueError(\"n must not be negative\")\n    return sorted(samples, reverse=True)[:n]\n\n\ndef summary(samples: Sequence[int], budget_ms: int) -> dict[str, float]:\n    \"\"\"Mean, worst sample and over-budget ratio in one dict.\"\"\"\n    return {\n        \"mean\": mean_ms(samples),\n        \"worst\": float(max(samples)) if samples else 0.0,\n        \"over_budget\": over_budget_ratio(samples, budget_ms),\n    }\n"
  },
  {
   "id": "08-cart-summary",
   "title": "Shopping cart summary",
   "difficulty": "easy",
   "bugKind": "missing empty-input edge case",
   "description": "This module summarizes the prices in a shopping cart. cart_summary returns a dict with the item count, the total, the average price rounded half-up to cents, and the most expensive price. For an empty cart it returns a count of 0, zero amounts for total and average, and None for the maximum.",
   "buggy.py": "\"\"\"Summaries for shopping carts.\"\"\"\nfrom __future__ import annotations\n\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Sequence\n\nZERO = Decimal(\"0.00\")\nCENT = Decimal(\"0.01\")\n\n\ndef cart_summary(prices: Sequence[Decimal]) -> dict:\n    \"\"\"Count, total, average (cents, half-up) and maximum of the prices.\n\n    An empty cart gives count 0, zero total and average, and max None.\n    \"\"\"\n    total = sum(prices, ZERO)\n    average = (total / len(prices)).quantize(CENT, rounding=ROUND_HALF_UP)\n    return {\n        \"count\": len(prices),\n        \"total\": total,\n        \"average\": average,\n        \"max\": max(prices),\n    }\n\n\ndef free_shipping_gap(prices: Sequence[Decimal], threshold: Decimal) -> Decimal:\n    \"\"\"How much more must be added to reach free shipping (never negative).\"\"\"\n    total = sum(prices, ZERO)\n    return max(threshold - total, ZERO)\n\n\ndef describe(prices: Sequence[Decimal]) -> str:\n    \"\"\"One-line human readable summary.\"\"\"\n    info = cart_summary(prices)\n    if info[\"count\"] == 0:\n        return \"empty cart\"\n    return f\"{info['count']} items, total {info['total']}\"\n",
   "test_visible.py": "import unittest\nfrom decimal import Decimal\nfrom solution import cart_summary\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_empty_cart(self):\n        info = cart_summary([])\n        self.assertEqual(info[\"count\"], 0)\n        self.assertEqual(info[\"total\"], Decimal(\"0\"))\n        self.assertIsNone(info[\"max\"])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom decimal import Decimal as D\nfrom solution import cart_summary, free_shipping_gap, describe\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_empty_full_dict(self):\n        self.assertEqual(cart_summary([]), {\"count\": 0, \"total\": D(\"0.00\"),\n                                            \"average\": D(\"0.00\"), \"max\": None})\n\n    def test_single(self):\n        info = cart_summary([D(\"9.99\")])\n        self.assertEqual(info[\"count\"], 1)\n        self.assertEqual(info[\"average\"], D(\"9.99\"))\n        self.assertEqual(info[\"max\"], D(\"9.99\"))\n\n    def test_total_and_max(self):\n        info = cart_summary([D(\"1.50\"), D(\"20.00\"), D(\"3.25\")])\n        self.assertEqual(info[\"total\"], D(\"24.75\"))\n        self.assertEqual(info[\"max\"], D(\"20.00\"))\n\n    def test_average_half_up(self):\n        self.assertEqual(cart_summary([D(\"1.00\"), D(\"1.01\")])[\"average\"], D(\"1.01\"))\n\n    def test_average_rounds_down(self):\n        self.assertEqual(cart_summary([D(\"1.00\"), D(\"1.00\"), D(\"1.01\")])[\"average\"], D(\"1.00\"))\n\n    def test_tuple_input(self):\n        self.assertEqual(cart_summary((D(\"2\"), D(\"4\")))[\"average\"], D(\"3.00\"))\n\n    def test_gap(self):\n        self.assertEqual(free_shipping_gap([D(\"30\"), D(\"5.50\")], D(\"50\")), D(\"14.50\"))\n\n    def test_gap_never_negative(self):\n        self.assertEqual(free_shipping_gap([D(\"60\")], D(\"50\")), D(\"0\"))\n        self.assertEqual(free_shipping_gap([], D(\"50\")), D(\"50\"))\n\n    def test_describe(self):\n        self.assertEqual(describe([]), \"empty cart\")\n        self.assertEqual(describe([D(\"1\"), D(\"2\")]), \"2 items, total 3.00\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Summaries for shopping carts.\"\"\"\nfrom __future__ import annotations\n\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Sequence\n\nZERO = Decimal(\"0.00\")\nCENT = Decimal(\"0.01\")\n\n\ndef cart_summary(prices: Sequence[Decimal]) -> dict:\n    \"\"\"Count, total, average (cents, half-up) and maximum of the prices.\n\n    An empty cart gives count 0, zero total and average, and max None.\n    \"\"\"\n    if not prices:\n        return {\"count\": 0, \"total\": ZERO, \"average\": ZERO, \"max\": None}\n    total = sum(prices, ZERO)\n    average = (total / len(prices)).quantize(CENT, rounding=ROUND_HALF_UP)\n    return {\n        \"count\": len(prices),\n        \"total\": total,\n        \"average\": average,\n        \"max\": max(prices),\n    }\n\n\ndef free_shipping_gap(prices: Sequence[Decimal], threshold: Decimal) -> Decimal:\n    \"\"\"How much more must be added to reach free shipping (never negative).\"\"\"\n    total = sum(prices, ZERO)\n    return max(threshold - total, ZERO)\n\n\ndef describe(prices: Sequence[Decimal]) -> str:\n    \"\"\"One-line human readable summary.\"\"\"\n    info = cart_summary(prices)\n    if info[\"count\"] == 0:\n        return \"empty cart\"\n    return f\"{info['count']} items, total {info['total']}\"\n"
  },
  {
   "id": "09-version-compare",
   "title": "Version string comparison",
   "difficulty": "medium",
   "bugKind": "string vs integer comparison",
   "description": "This module compares dotted version strings such as '1.10.2' or 'v2.0'. parse_version returns a tuple of integers (an optional leading 'v' is ignored, non-numeric parts raise ValueError). compare_versions returns -1, 0 or 1, treating missing trailing parts as zero, so '1.0' equals '1.0.0'. newest picks the highest version string and is_compatible checks a half-open range.",
   "buggy.py": "\"\"\"Dotted version string comparison.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable\n\n\ndef parse_version(text: str) -> tuple[int, ...]:\n    \"\"\"'v1.2.3' -> (1, 2, 3). Raises ValueError on non-numeric parts.\"\"\"\n    cleaned = text.strip()\n    if cleaned[:1] in (\"v\", \"V\"):\n        cleaned = cleaned[1:]\n    parts = cleaned.split(\".\")\n    return tuple(parts)\n\n\ndef compare_versions(a: str, b: str) -> int:\n    \"\"\"-1 if a < b, 0 if equal, 1 if a > b; missing parts count as zero.\"\"\"\n    pa, pb = parse_version(a), parse_version(b)\n    size = max(len(pa), len(pb))\n    pa += (0,) * (size - len(pa))\n    pb += (0,) * (size - len(pb))\n    if pa < pb:\n        return -1\n    if pa > pb:\n        return 1\n    return 0\n\n\ndef newest(versions: Iterable[str]) -> str:\n    \"\"\"The highest version; the first one wins among equal versions.\"\"\"\n    best: str | None = None\n    for v in versions:\n        if best is None or compare_versions(v, best) > 0:\n            best = v\n    if best is None:\n        raise ValueError(\"no versions given\")\n    return best\n\n\ndef is_compatible(version: str, minimum: str, below: str) -> bool:\n    \"\"\"True when minimum <= version < below.\"\"\"\n    return compare_versions(version, minimum) >= 0 and compare_versions(version, below) < 0\n",
   "test_visible.py": "import unittest\nfrom solution import compare_versions\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_numeric_not_lexicographic(self):\n        self.assertEqual(compare_versions(\"1.10.0\", \"1.9.0\"), 1)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import parse_version, compare_versions, newest, is_compatible\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_parse(self):\n        self.assertEqual(parse_version(\"1.10.2\"), (1, 10, 2))\n        self.assertEqual(parse_version(\"v2.0\"), (2, 0))\n        self.assertEqual(parse_version(\" V3 \"), (3,))\n\n    def test_parse_invalid(self):\n        with self.assertRaises(ValueError):\n            parse_version(\"1.x.3\")\n\n    def test_less(self):\n        self.assertEqual(compare_versions(\"1.2.9\", \"1.10.0\"), -1)\n        self.assertEqual(compare_versions(\"2\", \"10\"), -1)\n\n    def test_greater(self):\n        self.assertEqual(compare_versions(\"1.9.0\", \"1.10.0\"), -1)\n        self.assertEqual(compare_versions(\"10.0\", \"9.99\"), 1)\n\n    def test_equal_with_padding(self):\n        self.assertEqual(compare_versions(\"1.0\", \"1.0.0\"), 0)\n        self.assertEqual(compare_versions(\"v1.2\", \"1.2.0.0\"), 0)\n\n    def test_padding_ordering(self):\n        self.assertEqual(compare_versions(\"1.0.1\", \"1.0\"), 1)\n        self.assertEqual(compare_versions(\"1.0\", \"1.0.1\"), -1)\n\n    def test_leading_zeros_numeric(self):\n        self.assertEqual(compare_versions(\"1.02\", \"1.2\"), 0)\n\n    def test_newest(self):\n        self.assertEqual(newest([\"1.9\", \"1.10\", \"1.2\"]), \"1.10\")\n\n    def test_newest_first_of_equals(self):\n        self.assertEqual(newest([\"1.0\", \"1.0.0\"]), \"1.0\")\n\n    def test_newest_empty(self):\n        with self.assertRaises(ValueError):\n            newest([])\n\n    def test_compat(self):\n        self.assertTrue(is_compatible(\"1.10\", \"1.9\", \"2.0\"))\n        self.assertTrue(is_compatible(\"1.9\", \"1.9\", \"2.0\"))\n        self.assertFalse(is_compatible(\"2.0\", \"1.9\", \"2.0\"))\n        self.assertFalse(is_compatible(\"1.8.9\", \"1.9\", \"2.0\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Dotted version string comparison.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable\n\n\ndef parse_version(text: str) -> tuple[int, ...]:\n    \"\"\"'v1.2.3' -> (1, 2, 3). Raises ValueError on non-numeric parts.\"\"\"\n    cleaned = text.strip()\n    if cleaned[:1] in (\"v\", \"V\"):\n        cleaned = cleaned[1:]\n    parts = cleaned.split(\".\")\n    return tuple(int(p) for p in parts)\n\n\ndef compare_versions(a: str, b: str) -> int:\n    \"\"\"-1 if a < b, 0 if equal, 1 if a > b; missing parts count as zero.\"\"\"\n    pa, pb = parse_version(a), parse_version(b)\n    size = max(len(pa), len(pb))\n    pa += (0,) * (size - len(pa))\n    pb += (0,) * (size - len(pb))\n    if pa < pb:\n        return -1\n    if pa > pb:\n        return 1\n    return 0\n\n\ndef newest(versions: Iterable[str]) -> str:\n    \"\"\"The highest version; the first one wins among equal versions.\"\"\"\n    best: str | None = None\n    for v in versions:\n        if best is None or compare_versions(v, best) > 0:\n            best = v\n    if best is None:\n        raise ValueError(\"no versions given\")\n    return best\n\n\ndef is_compatible(version: str, minimum: str, below: str) -> bool:\n    \"\"\"True when minimum <= version < below.\"\"\"\n    return compare_versions(version, minimum) >= 0 and compare_versions(version, below) < 0\n"
  },
  {
   "id": "10-token-bucket",
   "title": "Token bucket rate limiter",
   "difficulty": "hard",
   "bugKind": "wrong variable in derived calculation",
   "description": "This module implements a token bucket rate limiter with an injected clock (callers pass the current time in seconds). The bucket starts full and refills at a fixed rate up to its capacity. allow consumes tokens when enough are available and returns whether it did. retry_after returns how many seconds the caller must wait until a request of that cost would be allowed (0.0 if it would be allowed now) without consuming anything. Costs above the capacity raise ValueError.",
   "buggy.py": "\"\"\"Token bucket rate limiter driven by an injected clock.\"\"\"\nfrom __future__ import annotations\n\n\nclass TokenBucket:\n    \"\"\"Bucket with ``capacity`` tokens refilling at ``refill_per_sec``.\"\"\"\n\n    def __init__(self, capacity: float, refill_per_sec: float, start: float = 0.0) -> None:\n        if capacity <= 0 or refill_per_sec <= 0:\n            raise ValueError(\"capacity and refill rate must be positive\")\n        self.capacity = float(capacity)\n        self.refill_per_sec = float(refill_per_sec)\n        self._tokens = float(capacity)\n        self._last = start\n\n    def _refill(self, now: float) -> None:\n        \"\"\"Add the tokens earned since the last update.\"\"\"\n        elapsed = max(0.0, now - self._last)\n        self._tokens = min(self.capacity, self._tokens + elapsed * self.refill_per_sec)\n        self._last = max(self._last, now)\n\n    def _check_cost(self, cost: float) -> None:\n        if cost <= 0 or cost > self.capacity:\n            raise ValueError(\"cost must be in (0, capacity]\")\n\n    def allow(self, now: float, cost: float = 1.0) -> bool:\n        \"\"\"Consume ``cost`` tokens if available at time ``now``.\"\"\"\n        self._check_cost(cost)\n        self._refill(now)\n        if self._tokens >= cost:\n            self._tokens -= cost\n            return True\n        return False\n\n    def retry_after(self, now: float, cost: float = 1.0) -> float:\n        \"\"\"Seconds until ``cost`` tokens will be available (0.0 if now).\"\"\"\n        self._check_cost(cost)\n        self._refill(now)\n        missing = cost - self._tokens\n        if missing <= 0:\n            return 0.0\n        return missing / self.capacity\n\n    def tokens(self, now: float) -> float:\n        \"\"\"Tokens currently available.\"\"\"\n        self._refill(now)\n        return self._tokens\n",
   "test_visible.py": "import unittest\nfrom solution import TokenBucket\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_retry_after_waits_for_missing_tokens(self):\n        bucket = TokenBucket(capacity=10, refill_per_sec=2)\n        self.assertTrue(bucket.allow(0, cost=10))\n        self.assertEqual(bucket.retry_after(0, cost=4), 2.0)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import TokenBucket\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_starts_full(self):\n        b = TokenBucket(3, 1)\n        self.assertTrue(b.allow(0))\n        self.assertTrue(b.allow(0))\n        self.assertTrue(b.allow(0))\n        self.assertFalse(b.allow(0))\n\n    def test_refill(self):\n        b = TokenBucket(4, 2)\n        self.assertTrue(b.allow(0, 4))\n        self.assertFalse(b.allow(0.4, 1))\n        self.assertTrue(b.allow(0.5, 1))\n\n    def test_capped_at_capacity(self):\n        b = TokenBucket(5, 10)\n        b.allow(0, 5)\n        self.assertEqual(b.tokens(100), 5.0)\n\n    def test_retry_after_zero_when_available(self):\n        b = TokenBucket(5, 1)\n        self.assertEqual(b.retry_after(0, 3), 0.0)\n\n    def test_retry_after_depends_on_rate(self):\n        b = TokenBucket(10, 5)\n        b.allow(0, 10)\n        self.assertEqual(b.retry_after(0, 5), 1.0)\n        self.assertEqual(b.retry_after(0, 10), 2.0)\n\n    def test_retry_after_slow_refill(self):\n        b = TokenBucket(2, 0.5)\n        b.allow(0, 2)\n        self.assertEqual(b.retry_after(0, 1), 2.0)\n\n    def test_retry_after_accounts_for_partial_refill(self):\n        b = TokenBucket(10, 2)\n        b.allow(0, 10)\n        self.assertEqual(b.retry_after(1, 6), 2.0)\n\n    def test_allow_succeeds_after_retry_after(self):\n        b = TokenBucket(8, 4)\n        b.allow(0, 8)\n        wait = b.retry_after(0, 6)\n        self.assertEqual(wait, 1.5)\n        self.assertFalse(b.allow(wait - 0.25, 6))\n        self.assertTrue(b.allow(wait, 6))\n\n    def test_retry_after_does_not_consume(self):\n        b = TokenBucket(4, 1)\n        b.retry_after(0, 4)\n        self.assertTrue(b.allow(0, 4))\n\n    def test_cost_validation(self):\n        b = TokenBucket(4, 1)\n        with self.assertRaises(ValueError):\n            b.allow(0, 5)\n        with self.assertRaises(ValueError):\n            b.retry_after(0, 5)\n        with self.assertRaises(ValueError):\n            b.allow(0, 0)\n\n    def test_constructor_validation(self):\n        with self.assertRaises(ValueError):\n            TokenBucket(0, 1)\n        with self.assertRaises(ValueError):\n            TokenBucket(1, 0)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Token bucket rate limiter driven by an injected clock.\"\"\"\nfrom __future__ import annotations\n\n\nclass TokenBucket:\n    \"\"\"Bucket with ``capacity`` tokens refilling at ``refill_per_sec``.\"\"\"\n\n    def __init__(self, capacity: float, refill_per_sec: float, start: float = 0.0) -> None:\n        if capacity <= 0 or refill_per_sec <= 0:\n            raise ValueError(\"capacity and refill rate must be positive\")\n        self.capacity = float(capacity)\n        self.refill_per_sec = float(refill_per_sec)\n        self._tokens = float(capacity)\n        self._last = start\n\n    def _refill(self, now: float) -> None:\n        \"\"\"Add the tokens earned since the last update.\"\"\"\n        elapsed = max(0.0, now - self._last)\n        self._tokens = min(self.capacity, self._tokens + elapsed * self.refill_per_sec)\n        self._last = max(self._last, now)\n\n    def _check_cost(self, cost: float) -> None:\n        if cost <= 0 or cost > self.capacity:\n            raise ValueError(\"cost must be in (0, capacity]\")\n\n    def allow(self, now: float, cost: float = 1.0) -> bool:\n        \"\"\"Consume ``cost`` tokens if available at time ``now``.\"\"\"\n        self._check_cost(cost)\n        self._refill(now)\n        if self._tokens >= cost:\n            self._tokens -= cost\n            return True\n        return False\n\n    def retry_after(self, now: float, cost: float = 1.0) -> float:\n        \"\"\"Seconds until ``cost`` tokens will be available (0.0 if now).\"\"\"\n        self._check_cost(cost)\n        self._refill(now)\n        missing = cost - self._tokens\n        if missing <= 0:\n            return 0.0\n        return missing / self.refill_per_sec\n\n    def tokens(self, now: float) -> float:\n        \"\"\"Tokens currently available.\"\"\"\n        self._refill(now)\n        return self._tokens\n"
  },
  {
   "id": "11-retry-backoff",
   "title": "Retry backoff schedule",
   "difficulty": "medium",
   "bugKind": "min/max swapped",
   "description": "This module builds exponential backoff schedules for retries. backoff_schedule returns the delay before each retry as base * factor**i, never more than cap seconds. total_wait sums a schedule, and attempts_within returns how many consecutive retries fit into a time budget when their delays are added up. Negative attempt counts or a non-positive base raise ValueError.",
   "buggy.py": "\"\"\"Exponential backoff schedules for retrying failed calls.\"\"\"\nfrom __future__ import annotations\n\n\ndef backoff_schedule(attempts: int, base: float = 0.5, factor: float = 2.0,\n                     cap: float = 30.0) -> list[float]:\n    \"\"\"Delay in seconds before each of ``attempts`` retries.\n\n    The i-th delay (from 0) is ``base * factor ** i``, limited to ``cap``.\n    \"\"\"\n    if attempts < 0:\n        raise ValueError(\"attempts must not be negative\")\n    if base <= 0 or factor < 1 or cap <= 0:\n        raise ValueError(\"invalid backoff parameters\")\n    delays: list[float] = []\n    for i in range(attempts):\n        delays.append(max(cap, base * factor ** i))\n    return delays\n\n\ndef total_wait(schedule: list[float]) -> float:\n    \"\"\"Sum of all delays in a schedule.\"\"\"\n    return sum(schedule)\n\n\ndef attempts_within(budget: float, base: float = 0.5, factor: float = 2.0,\n                    cap: float = 30.0, max_attempts: int = 50) -> int:\n    \"\"\"How many retries fit in ``budget`` seconds of cumulative waiting.\"\"\"\n    spent = 0.0\n    count = 0\n    for delay in backoff_schedule(max_attempts, base, factor, cap):\n        if spent + delay > budget:\n            break\n        spent += delay\n        count += 1\n    return count\n",
   "test_visible.py": "import unittest\nfrom solution import backoff_schedule\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_delays_are_capped(self):\n        self.assertEqual(backoff_schedule(5, base=1, factor=2, cap=8), [1, 2, 4, 8, 8])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import backoff_schedule, total_wait, attempts_within\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_uncapped_growth(self):\n        self.assertEqual(backoff_schedule(4, base=1, factor=2, cap=100), [1, 2, 4, 8])\n\n    def test_defaults(self):\n        self.assertEqual(backoff_schedule(3), [0.5, 1.0, 2.0])\n\n    def test_cap_applies(self):\n        self.assertEqual(backoff_schedule(4, base=10, factor=3, cap=50), [10, 30, 50, 50])\n\n    def test_cap_below_base(self):\n        self.assertEqual(backoff_schedule(2, base=10, cap=5), [5, 5])\n\n    def test_factor_one(self):\n        self.assertEqual(backoff_schedule(3, base=2, factor=1, cap=10), [2, 2, 2])\n\n    def test_zero_attempts(self):\n        self.assertEqual(backoff_schedule(0), [])\n\n    def test_validation(self):\n        with self.assertRaises(ValueError):\n            backoff_schedule(-1)\n        with self.assertRaises(ValueError):\n            backoff_schedule(3, base=0)\n\n    def test_total_wait(self):\n        self.assertEqual(total_wait(backoff_schedule(4, base=1, cap=100)), 15)\n        self.assertEqual(total_wait([]), 0)\n\n    def test_attempts_within(self):\n        self.assertEqual(attempts_within(7, base=1, factor=2, cap=100), 3)\n        self.assertEqual(attempts_within(6.9, base=1, factor=2, cap=100), 2)\n\n    def test_attempts_within_small_budget(self):\n        self.assertEqual(attempts_within(0.1), 0)\n\n    def test_attempts_within_capped(self):\n        self.assertEqual(attempts_within(100, base=10, factor=2, cap=20), 5)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Exponential backoff schedules for retrying failed calls.\"\"\"\nfrom __future__ import annotations\n\n\ndef backoff_schedule(attempts: int, base: float = 0.5, factor: float = 2.0,\n                     cap: float = 30.0) -> list[float]:\n    \"\"\"Delay in seconds before each of ``attempts`` retries.\n\n    The i-th delay (from 0) is ``base * factor ** i``, limited to ``cap``.\n    \"\"\"\n    if attempts < 0:\n        raise ValueError(\"attempts must not be negative\")\n    if base <= 0 or factor < 1 or cap <= 0:\n        raise ValueError(\"invalid backoff parameters\")\n    delays: list[float] = []\n    for i in range(attempts):\n        delays.append(min(cap, base * factor ** i))\n    return delays\n\n\ndef total_wait(schedule: list[float]) -> float:\n    \"\"\"Sum of all delays in a schedule.\"\"\"\n    return sum(schedule)\n\n\ndef attempts_within(budget: float, base: float = 0.5, factor: float = 2.0,\n                    cap: float = 30.0, max_attempts: int = 50) -> int:\n    \"\"\"How many retries fit in ``budget`` seconds of cumulative waiting.\"\"\"\n    spent = 0.0\n    count = 0\n    for delay in backoff_schedule(max_attempts, base, factor, cap):\n        if spent + delay > budget:\n            break\n        spent += delay\n        count += 1\n    return count\n"
  },
  {
   "id": "12-room-bookings",
   "title": "Room booking availability",
   "difficulty": "medium",
   "bugKind": "wrong boundary in date range",
   "description": "This module checks hotel room bookings. A booking occupies the nights from check-in up to, but not including, the check-out day, so a stay may start on the day another one ends. overlaps tests two such ranges, is_available checks a requested stay against existing bookings, and occupancy counts the booked room-nights inside a window that also excludes its end day. Ranges whose end is not after their start raise ValueError.",
   "buggy.py": "\"\"\"Room booking checks using half-open night ranges.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom datetime import date, timedelta\nfrom typing import Iterable\n\n\n@dataclass(frozen=True)\nclass Booking:\n    \"\"\"A stay from ``check_in`` (inclusive) to ``check_out`` (exclusive).\"\"\"\n\n    guest: str\n    check_in: date\n    check_out: date\n\n\ndef _validate(start: date, end: date) -> None:\n    if end <= start:\n        raise ValueError(\"end must be after start\")\n\n\ndef nights(booking: Booking) -> int:\n    \"\"\"Number of nights of the booking.\"\"\"\n    _validate(booking.check_in, booking.check_out)\n    return (booking.check_out - booking.check_in).days\n\n\ndef overlaps(a_in: date, a_out: date, b_in: date, b_out: date) -> bool:\n    \"\"\"True when two stays share at least one night.\"\"\"\n    _validate(a_in, a_out)\n    _validate(b_in, b_out)\n    return a_in <= b_out and b_in <= a_out\n\n\ndef is_available(bookings: Iterable[Booking], check_in: date, check_out: date) -> bool:\n    \"\"\"True when the requested stay collides with no existing booking.\"\"\"\n    _validate(check_in, check_out)\n    return not any(overlaps(b.check_in, b.check_out, check_in, check_out) for b in bookings)\n\n\ndef occupancy(bookings: Iterable[Booking], start: date, end: date) -> int:\n    \"\"\"Booked room-nights within [start, end).\"\"\"\n    _validate(start, end)\n    total = 0\n    day = start\n    while day < end:\n        total += sum(1 for b in bookings if b.check_in <= day < b.check_out)\n        day += timedelta(days=1)\n    return total\n",
   "test_visible.py": "import unittest\nfrom datetime import date\nfrom solution import is_available, Booking\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_back_to_back_stays_do_not_collide(self):\n        existing = [Booking(\"ann\", date(2025, 3, 1), date(2025, 3, 4))]\n        self.assertTrue(is_available(existing, date(2025, 3, 4), date(2025, 3, 6)))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom datetime import date\nfrom solution import Booking, nights, overlaps, is_available, occupancy\n\nD = lambda d: date(2025, 3, d)\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_nights(self):\n        self.assertEqual(nights(Booking(\"a\", D(1), D(4))), 3)\n\n    def test_overlap_partial(self):\n        self.assertTrue(overlaps(D(1), D(5), D(4), D(8)))\n        self.assertTrue(overlaps(D(4), D(8), D(1), D(5)))\n\n    def test_overlap_contained(self):\n        self.assertTrue(overlaps(D(1), D(10), D(3), D(4)))\n        self.assertTrue(overlaps(D(3), D(4), D(1), D(10)))\n\n    def test_adjacent_both_directions(self):\n        self.assertFalse(overlaps(D(1), D(4), D(4), D(6)))\n        self.assertFalse(overlaps(D(4), D(6), D(1), D(4)))\n\n    def test_disjoint(self):\n        self.assertFalse(overlaps(D(1), D(2), D(5), D(6)))\n\n    def test_one_night_collision(self):\n        self.assertTrue(overlaps(D(1), D(4), D(3), D(4)))\n\n    def test_available_and_blocked(self):\n        existing = [Booking(\"a\", D(1), D(4)), Booking(\"b\", D(6), D(9))]\n        self.assertTrue(is_available(existing, D(4), D(6)))\n        self.assertFalse(is_available(existing, D(3), D(5)))\n        self.assertFalse(is_available(existing, D(5), D(7)))\n        self.assertTrue(is_available([], D(1), D(2)))\n\n    def test_invalid_range(self):\n        with self.assertRaises(ValueError):\n            is_available([], D(5), D(5))\n        with self.assertRaises(ValueError):\n            overlaps(D(5), D(4), D(1), D(2))\n\n    def test_occupancy(self):\n        existing = [Booking(\"a\", D(1), D(4)), Booking(\"b\", D(3), D(6))]\n        self.assertEqual(occupancy(existing, D(1), D(7)), 6)\n        self.assertEqual(occupancy(existing, D(3), D(4)), 2)\n        self.assertEqual(occupancy(existing, D(4), D(5)), 1)\n\n    def test_occupancy_window_end_excluded(self):\n        existing = [Booking(\"a\", D(5), D(8))]\n        self.assertEqual(occupancy(existing, D(1), D(5)), 0)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Room booking checks using half-open night ranges.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom datetime import date, timedelta\nfrom typing import Iterable\n\n\n@dataclass(frozen=True)\nclass Booking:\n    \"\"\"A stay from ``check_in`` (inclusive) to ``check_out`` (exclusive).\"\"\"\n\n    guest: str\n    check_in: date\n    check_out: date\n\n\ndef _validate(start: date, end: date) -> None:\n    if end <= start:\n        raise ValueError(\"end must be after start\")\n\n\ndef nights(booking: Booking) -> int:\n    \"\"\"Number of nights of the booking.\"\"\"\n    _validate(booking.check_in, booking.check_out)\n    return (booking.check_out - booking.check_in).days\n\n\ndef overlaps(a_in: date, a_out: date, b_in: date, b_out: date) -> bool:\n    \"\"\"True when two stays share at least one night.\"\"\"\n    _validate(a_in, a_out)\n    _validate(b_in, b_out)\n    return a_in < b_out and b_in < a_out\n\n\ndef is_available(bookings: Iterable[Booking], check_in: date, check_out: date) -> bool:\n    \"\"\"True when the requested stay collides with no existing booking.\"\"\"\n    _validate(check_in, check_out)\n    return not any(overlaps(b.check_in, b.check_out, check_in, check_out) for b in bookings)\n\n\ndef occupancy(bookings: Iterable[Booking], start: date, end: date) -> int:\n    \"\"\"Booked room-nights within [start, end).\"\"\"\n    _validate(start, end)\n    total = 0\n    day = start\n    while day < end:\n        total += sum(1 for b in bookings if b.check_in <= day < b.check_out)\n        day += timedelta(days=1)\n    return total\n"
  },
  {
   "id": "13-layered-config",
   "title": "Layered configuration merge",
   "difficulty": "easy",
   "bugKind": "dict merge precedence",
   "description": "This module merges configuration layers given from lowest to highest priority. deep_merge merges two dicts recursively, with values from the second dict winning (nested dicts are merged key by key). layered_config folds any number of layers this way without modifying its inputs, and get_path reads a dotted path such as 'db.port' with a default.",
   "buggy.py": "\"\"\"Layered configuration: defaults < file < environment < overrides.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Any\n\nConfig = dict[str, Any]\n\n\ndef deep_merge(base: Config, top: Config) -> Config:\n    \"\"\"Return a new dict where ``top`` wins; nested dicts merge recursively.\"\"\"\n    result = dict(base)\n    for key, value in top.items():\n        if isinstance(value, dict) and isinstance(result.get(key), dict):\n            result[key] = deep_merge(result[key], value)\n        else:\n            result[key] = value\n    return result\n\n\ndef layered_config(*layers: Config) -> Config:\n    \"\"\"Merge layers, later layers having higher priority.\"\"\"\n    result: Config = {}\n    for layer in layers:\n        result = deep_merge(layer, result)\n    return result\n\n\ndef get_path(config: Config, path: str, default: Any = None) -> Any:\n    \"\"\"Read ``a.b.c`` from nested dicts, or return ``default``.\"\"\"\n    node: Any = config\n    for part in path.split(\".\"):\n        if not isinstance(node, dict) or part not in node:\n            return default\n        node = node[part]\n    return node\n",
   "test_visible.py": "import unittest\nfrom solution import layered_config\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_later_layer_wins(self):\n        merged = layered_config({\"port\": 80, \"debug\": False}, {\"port\": 8080})\n        self.assertEqual(merged, {\"port\": 8080, \"debug\": False})\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import deep_merge, layered_config, get_path\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_three_layers(self):\n        merged = layered_config({\"a\": 1, \"b\": 1, \"c\": 1}, {\"b\": 2, \"c\": 2}, {\"c\": 3})\n        self.assertEqual(merged, {\"a\": 1, \"b\": 2, \"c\": 3})\n\n    def test_nested_merge(self):\n        merged = layered_config({\"db\": {\"host\": \"x\", \"port\": 1}}, {\"db\": {\"port\": 2}})\n        self.assertEqual(merged, {\"db\": {\"host\": \"x\", \"port\": 2}})\n\n    def test_scalar_replaces_dict(self):\n        self.assertEqual(deep_merge({\"a\": {\"b\": 1}}, {\"a\": 5}), {\"a\": 5})\n\n    def test_dict_replaces_scalar(self):\n        self.assertEqual(deep_merge({\"a\": 5}, {\"a\": {\"b\": 1}}), {\"a\": {\"b\": 1}})\n\n    def test_inputs_not_modified(self):\n        low = {\"db\": {\"port\": 1}}\n        high = {\"db\": {\"port\": 2}}\n        layered_config(low, high)\n        self.assertEqual(low, {\"db\": {\"port\": 1}})\n        self.assertEqual(high, {\"db\": {\"port\": 2}})\n\n    def test_no_layers_and_empty_layers(self):\n        self.assertEqual(layered_config(), {})\n        self.assertEqual(layered_config({}, {\"a\": 1}, {}), {\"a\": 1})\n\n    def test_none_value_overrides(self):\n        self.assertEqual(layered_config({\"a\": 1}, {\"a\": None}), {\"a\": None})\n\n    def test_get_path(self):\n        cfg = {\"db\": {\"port\": 5432}, \"name\": \"x\"}\n        self.assertEqual(get_path(cfg, \"db.port\"), 5432)\n        self.assertEqual(get_path(cfg, \"name\"), \"x\")\n\n    def test_get_path_default(self):\n        cfg = {\"db\": {\"port\": 5432}}\n        self.assertEqual(get_path(cfg, \"db.host\", \"localhost\"), \"localhost\")\n        self.assertIsNone(get_path(cfg, \"x.y\"))\n        self.assertEqual(get_path(cfg, \"db.port.deeper\", 0), 0)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Layered configuration: defaults < file < environment < overrides.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Any\n\nConfig = dict[str, Any]\n\n\ndef deep_merge(base: Config, top: Config) -> Config:\n    \"\"\"Return a new dict where ``top`` wins; nested dicts merge recursively.\"\"\"\n    result = dict(base)\n    for key, value in top.items():\n        if isinstance(value, dict) and isinstance(result.get(key), dict):\n            result[key] = deep_merge(result[key], value)\n        else:\n            result[key] = value\n    return result\n\n\ndef layered_config(*layers: Config) -> Config:\n    \"\"\"Merge layers, later layers having higher priority.\"\"\"\n    result: Config = {}\n    for layer in layers:\n        result = deep_merge(result, layer)\n    return result\n\n\ndef get_path(config: Config, path: str, default: Any = None) -> Any:\n    \"\"\"Read ``a.b.c`` from nested dicts, or return ``default``.\"\"\"\n    node: Any = config\n    for part in path.split(\".\"):\n        if not isinstance(node, dict) or part not in node:\n            return default\n        node = node[part]\n    return node\n"
  },
  {
   "id": "14-password-policy",
   "title": "Password policy checker",
   "difficulty": "medium",
   "bugKind": "early return inside loop",
   "description": "This module checks passwords against a fixed list of rules. check_password returns the names of all rules that the password breaks, in rule order (length, digit, upper, lower, no_username, no_space), or an empty list when the password is acceptable. is_valid says whether nothing failed and strength_label turns the number of passed rules into 'weak', 'ok' or 'strong'.",
   "buggy.py": "\"\"\"Password policy checks.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Callable\n\nRule = Callable[[str, str], bool]\n\nRULES: list[tuple[str, Rule]] = [\n    (\"length\", lambda pw, user: len(pw) >= 10),\n    (\"digit\", lambda pw, user: any(c.isdigit() for c in pw)),\n    (\"upper\", lambda pw, user: any(c.isupper() for c in pw)),\n    (\"lower\", lambda pw, user: any(c.islower() for c in pw)),\n    (\"no_username\", lambda pw, user: not user or user.lower() not in pw.lower()),\n    (\"no_space\", lambda pw, user: \" \" not in pw),\n]\n\n\ndef check_password(password: str, username: str = \"\") -> list[str]:\n    \"\"\"Names of the rules the password breaks, in rule order.\"\"\"\n    failures: list[str] = []\n    for name, rule in RULES:\n        if not rule(password, username):\n            failures.append(name)\n        return failures\n\n\ndef is_valid(password: str, username: str = \"\") -> bool:\n    \"\"\"True when no rule is broken.\"\"\"\n    return not check_password(password, username)\n\n\ndef strength_label(password: str, username: str = \"\") -> str:\n    \"\"\"'weak' (<= 3 rules passed), 'ok' (4 or 5) or 'strong' (all 6).\"\"\"\n    passed = len(RULES) - len(check_password(password, username))\n    if passed <= 3:\n        return \"weak\"\n    if passed < len(RULES):\n        return \"ok\"\n    return \"strong\"\n",
   "test_visible.py": "import unittest\nfrom solution import check_password\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_reports_every_broken_rule(self):\n        self.assertEqual(check_password(\"short\"), [\"length\", \"digit\", \"upper\"])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import check_password, is_valid, strength_label\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_valid_password(self):\n        self.assertEqual(check_password(\"Abcdefghij1\"), [])\n\n    def test_only_length(self):\n        self.assertEqual(check_password(\"Abcdef1\"), [\"length\"])\n\n    def test_only_digit(self):\n        self.assertEqual(check_password(\"Abcdefghijk\"), [\"digit\"])\n\n    def test_digit_and_upper(self):\n        self.assertEqual(check_password(\"abcdefghijk\"), [\"digit\", \"upper\"])\n\n    def test_lower_missing(self):\n        self.assertEqual(check_password(\"ABCDEFGHIJ1\"), [\"lower\"])\n\n    def test_username_inside(self):\n        self.assertEqual(check_password(\"xxPatxxxxx1A\", \"pat\"), [\"no_username\"])\n        self.assertEqual(check_password(\"xxPatxxxxx1A\"), [])\n\n    def test_whitespace(self):\n        self.assertEqual(check_password(\"Abcde fghij1\"), [\"no_space\"])\n\n    def test_many_failures_in_order(self):\n        self.assertEqual(check_password(\"1234 \", \"12\"),\n                         [\"length\", \"upper\", \"lower\", \"no_username\", \"no_space\"])\n\n    def test_empty_password(self):\n        self.assertEqual(check_password(\"\"), [\"length\", \"digit\", \"upper\", \"lower\"])\n\n    def test_is_valid(self):\n        self.assertTrue(is_valid(\"Abcdefghij1\"))\n        self.assertFalse(is_valid(\"abc\"))\n\n    def test_strength(self):\n        self.assertEqual(strength_label(\"Abcdefghij1\"), \"strong\")\n        self.assertEqual(strength_label(\"Abcdef1\"), \"ok\")\n        self.assertEqual(strength_label(\"abc\"), \"weak\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Password policy checks.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Callable\n\nRule = Callable[[str, str], bool]\n\nRULES: list[tuple[str, Rule]] = [\n    (\"length\", lambda pw, user: len(pw) >= 10),\n    (\"digit\", lambda pw, user: any(c.isdigit() for c in pw)),\n    (\"upper\", lambda pw, user: any(c.isupper() for c in pw)),\n    (\"lower\", lambda pw, user: any(c.islower() for c in pw)),\n    (\"no_username\", lambda pw, user: not user or user.lower() not in pw.lower()),\n    (\"no_space\", lambda pw, user: \" \" not in pw),\n]\n\n\ndef check_password(password: str, username: str = \"\") -> list[str]:\n    \"\"\"Names of the rules the password breaks, in rule order.\"\"\"\n    failures: list[str] = []\n    for name, rule in RULES:\n        if not rule(password, username):\n            failures.append(name)\n    return failures\n\n\ndef is_valid(password: str, username: str = \"\") -> bool:\n    \"\"\"True when no rule is broken.\"\"\"\n    return not check_password(password, username)\n\n\ndef strength_label(password: str, username: str = \"\") -> str:\n    \"\"\"'weak' (<= 3 rules passed), 'ok' (4 or 5) or 'strong' (all 6).\"\"\"\n    passed = len(RULES) - len(check_password(password, username))\n    if passed <= 3:\n        return \"weak\"\n    if passed < len(RULES):\n        return \"ok\"\n    return \"strong\"\n"
  },
  {
   "id": "15-normalize-weights",
   "title": "Weight normalization",
   "difficulty": "medium",
   "bugKind": "exhausted iterator reused",
   "description": "This module turns raw weights into shares. normalize_weights accepts any iterable of numbers (lists, tuples or generators) and returns a list of shares that sum to 1, in the original order; a total of zero raises ValueError. weighted_mean computes the mean of values weighted by normalized weights and top_share gives the combined share of the n largest weights.",
   "buggy.py": "\"\"\"Helpers for turning raw weights into shares.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable\n\n\ndef normalize_weights(values: Iterable[float]) -> list[float]:\n    \"\"\"Scale ``values`` so that they sum to 1, keeping their order.\n\n    Accepts any iterable. Raises ValueError when the total is zero.\n    \"\"\"\n    total = sum(values)\n    if total == 0:\n        raise ValueError(\"weights must not sum to zero\")\n    return [v / total for v in values]\n\n\ndef weighted_mean(values: Iterable[float], weights: Iterable[float]) -> float:\n    \"\"\"Mean of ``values`` weighted by ``weights`` (same length).\"\"\"\n    shares = normalize_weights(weights)\n    vals = list(values)\n    if len(vals) != len(shares):\n        raise ValueError(\"values and weights differ in length\")\n    return sum(v * s for v, s in zip(vals, shares))\n\n\ndef top_share(weights: Iterable[float], n: int) -> float:\n    \"\"\"Combined share of the ``n`` largest weights.\"\"\"\n    shares = normalize_weights(weights)\n    return sum(sorted(shares, reverse=True)[:n])\n",
   "test_visible.py": "import unittest\nfrom solution import normalize_weights\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_accepts_generator(self):\n        shares = normalize_weights(x for x in (1, 1, 2))\n        self.assertEqual(shares, [0.25, 0.25, 0.5])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import normalize_weights, weighted_mean, top_share\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_list(self):\n        self.assertEqual(normalize_weights([1, 3]), [0.25, 0.75])\n\n    def test_tuple(self):\n        self.assertEqual(normalize_weights((2, 2)), [0.5, 0.5])\n\n    def test_generator(self):\n        self.assertEqual(normalize_weights(i for i in range(1, 5)), [0.1, 0.2, 0.3, 0.4])\n\n    def test_map_object(self):\n        self.assertEqual(normalize_weights(map(float, [\"1\", \"1\"])), [0.5, 0.5])\n\n    def test_sums_to_one(self):\n        self.assertAlmostEqual(sum(normalize_weights(iter([3, 5, 7, 11]))), 1.0)\n\n    def test_zero_total(self):\n        with self.assertRaises(ValueError):\n            normalize_weights([0, 0])\n        with self.assertRaises(ValueError):\n            normalize_weights(iter([]))\n\n    def test_input_list_untouched(self):\n        raw = [1, 1]\n        normalize_weights(raw)\n        self.assertEqual(raw, [1, 1])\n\n    def test_weighted_mean_lists(self):\n        self.assertEqual(weighted_mean([10, 20], [1, 3]), 17.5)\n\n    def test_weighted_mean_generators(self):\n        self.assertEqual(weighted_mean((v for v in (10, 20)), (w for w in (1, 3))), 17.5)\n\n    def test_weighted_mean_length_mismatch(self):\n        with self.assertRaises(ValueError):\n            weighted_mean([1, 2, 3], [1, 1])\n\n    def test_top_share(self):\n        self.assertEqual(top_share((w for w in (1, 1, 2, 4)), 2), 0.75)\n        self.assertEqual(top_share([1, 1], 5), 1.0)\n        self.assertEqual(top_share([1, 3], 0), 0)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Helpers for turning raw weights into shares.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable\n\n\ndef normalize_weights(values: Iterable[float]) -> list[float]:\n    \"\"\"Scale ``values`` so that they sum to 1, keeping their order.\n\n    Accepts any iterable. Raises ValueError when the total is zero.\n    \"\"\"\n    values = list(values)\n    total = sum(values)\n    if total == 0:\n        raise ValueError(\"weights must not sum to zero\")\n    return [v / total for v in values]\n\n\ndef weighted_mean(values: Iterable[float], weights: Iterable[float]) -> float:\n    \"\"\"Mean of ``values`` weighted by ``weights`` (same length).\"\"\"\n    shares = normalize_weights(weights)\n    vals = list(values)\n    if len(vals) != len(shares):\n        raise ValueError(\"values and weights differ in length\")\n    return sum(v * s for v, s in zip(vals, shares))\n\n\ndef top_share(weights: Iterable[float], n: int) -> float:\n    \"\"\"Combined share of the ``n`` largest weights.\"\"\"\n    shares = normalize_weights(weights)\n    return sum(sorted(shares, reverse=True)[:n])\n"
  },
  {
   "id": "16-ellipsize",
   "title": "Text ellipsizing",
   "difficulty": "easy",
   "bugKind": "slicing mistake",
   "description": "This module shortens text for table cells. ellipsize returns the text unchanged if it fits within the limit; otherwise it returns a prefix followed by '...' so that the result is exactly limit characters long. middle_ellipsize keeps both the start and the end of the text with '...' in the middle, again exactly limit characters long. Limits below 3 raise ValueError.",
   "buggy.py": "\"\"\"Shorten strings for fixed-width displays.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable\n\nELLIPSIS = \"...\"\n\n\ndef ellipsize(text: str, limit: int) -> str:\n    \"\"\"Cut ``text`` to at most ``limit`` characters, ending in '...'.\"\"\"\n    if limit < len(ELLIPSIS):\n        raise ValueError(\"limit too small\")\n    if len(text) <= limit:\n        return text\n    return text[:-3] + \"...\"\n\n\ndef middle_ellipsize(text: str, limit: int) -> str:\n    \"\"\"Like ``ellipsize`` but keeps the start and the end of the text.\"\"\"\n    if limit < len(ELLIPSIS):\n        raise ValueError(\"limit too small\")\n    if len(text) <= limit:\n        return text\n    keep = limit - len(ELLIPSIS)\n    head = (keep + 1) // 2\n    tail = keep - head\n    return text[:head] + ELLIPSIS + text[len(text) - tail:]\n\n\ndef shorten_all(texts: Iterable[str], limit: int) -> list[str]:\n    \"\"\"Apply ``ellipsize`` to every text.\"\"\"\n    return [ellipsize(t, limit) for t in texts]\n",
   "test_visible.py": "import unittest\nfrom solution import ellipsize\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_long_text_is_cut_to_limit(self):\n        self.assertEqual(ellipsize(\"hello world\", 8), \"hello...\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import ellipsize, middle_ellipsize, shorten_all\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_short_text_unchanged(self):\n        self.assertEqual(ellipsize(\"abc\", 10), \"abc\")\n\n    def test_exact_fit_unchanged(self):\n        self.assertEqual(ellipsize(\"abcdef\", 6), \"abcdef\")\n\n    def test_one_over(self):\n        self.assertEqual(ellipsize(\"abcdefg\", 6), \"abc...\")\n\n    def test_length_equals_limit(self):\n        text = \"x\" * 50\n        for limit in range(3, 50):\n            self.assertEqual(len(ellipsize(text, limit)), limit)\n\n    def test_limit_three(self):\n        self.assertEqual(ellipsize(\"abcdef\", 3), \"...\")\n\n    def test_limit_too_small(self):\n        with self.assertRaises(ValueError):\n            ellipsize(\"abc\", 2)\n        with self.assertRaises(ValueError):\n            middle_ellipsize(\"abc\", 1)\n\n    def test_middle(self):\n        self.assertEqual(middle_ellipsize(\"abcdefghijklmnop\", 10), \"abcd...nop\")\n\n    def test_middle_even_keep(self):\n        self.assertEqual(middle_ellipsize(\"abcdefghijklmnop\", 9), \"abc...nop\")\n\n    def test_middle_limit_three(self):\n        self.assertEqual(middle_ellipsize(\"abcdef\", 3), \"...\")\n\n    def test_middle_short_unchanged(self):\n        self.assertEqual(middle_ellipsize(\"abc\", 5), \"abc\")\n\n    def test_shorten_all(self):\n        self.assertEqual(shorten_all([\"abcdefgh\", \"ab\", \"abcdefghijk\"], 7),\n                         [\"abcd...\", \"ab\", \"abcd...\"])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Shorten strings for fixed-width displays.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable\n\nELLIPSIS = \"...\"\n\n\ndef ellipsize(text: str, limit: int) -> str:\n    \"\"\"Cut ``text`` to at most ``limit`` characters, ending in '...'.\"\"\"\n    if limit < len(ELLIPSIS):\n        raise ValueError(\"limit too small\")\n    if len(text) <= limit:\n        return text\n    return text[:limit - 3] + \"...\"\n\n\ndef middle_ellipsize(text: str, limit: int) -> str:\n    \"\"\"Like ``ellipsize`` but keeps the start and the end of the text.\"\"\"\n    if limit < len(ELLIPSIS):\n        raise ValueError(\"limit too small\")\n    if len(text) <= limit:\n        return text\n    keep = limit - len(ELLIPSIS)\n    head = (keep + 1) // 2\n    tail = keep - head\n    return text[:head] + ELLIPSIS + text[len(text) - tail:]\n\n\ndef shorten_all(texts: Iterable[str], limit: int) -> list[str]:\n    \"\"\"Apply ``ellipsize`` to every text.\"\"\"\n    return [ellipsize(t, limit) for t in texts]\n"
  },
  {
   "id": "17-bundle-pricing",
   "title": "Nested bundle pricing",
   "difficulty": "medium",
   "bugKind": "wrong recursion base case",
   "description": "This module prices product bundles described as nested dicts. A leaf is {'price': Decimal, 'qty': int (optional, default 1)}; a bundle is {'items': [...], 'discount_percent': number (optional)} whose children are leaves or bundles. bundle_price returns the discounted total of a bundle (rounded half-up to cents), an empty bundle costs zero, count_items returns the total quantity of leaves, and depth returns how deeply bundles are nested.",
   "buggy.py": "\"\"\"Pricing for nested product bundles.\"\"\"\nfrom __future__ import annotations\n\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Any\n\nNode = dict[str, Any]\nCENT = Decimal(\"0.01\")\n\n\ndef bundle_price(node: Node) -> Decimal:\n    \"\"\"Total price of a leaf or bundle, applying bundle discounts.\"\"\"\n    if not node.get(\"items\"):\n        return node[\"price\"] * node.get(\"qty\", 1)\n    total = sum((bundle_price(child) for child in node[\"items\"]), Decimal(\"0\"))\n    discount = Decimal(node.get(\"discount_percent\", 0))\n    discounted = total * (Decimal(100) - discount) / Decimal(100)\n    return discounted.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef count_items(node: Node) -> int:\n    \"\"\"Total quantity of leaf items inside ``node``.\"\"\"\n    if \"items\" not in node:\n        return node.get(\"qty\", 1)\n    return sum(count_items(child) for child in node[\"items\"])\n\n\ndef depth(node: Node) -> int:\n    \"\"\"0 for a leaf, 1 for a bundle of leaves, and so on.\"\"\"\n    if \"items\" not in node:\n        return 0\n    return 1 + max((depth(child) for child in node[\"items\"]), default=0)\n",
   "test_visible.py": "import unittest\nfrom decimal import Decimal\nfrom solution import bundle_price\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_empty_sub_bundle_costs_nothing(self):\n        bundle = {\"items\": [{\"price\": Decimal(\"10.00\")}, {\"items\": []}]}\n        self.assertEqual(bundle_price(bundle), Decimal(\"10.00\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom decimal import Decimal as D\nfrom solution import bundle_price, count_items, depth\n\n\ndef leaf(price, qty=None):\n    node = {\"price\": D(price)}\n    if qty is not None:\n        node[\"qty\"] = qty\n    return node\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_leaf(self):\n        self.assertEqual(bundle_price(leaf(\"4.50\")), D(\"4.50\"))\n\n    def test_leaf_quantity(self):\n        self.assertEqual(bundle_price(leaf(\"4.50\", 3)), D(\"13.50\"))\n\n    def test_flat_bundle(self):\n        self.assertEqual(bundle_price({\"items\": [leaf(\"1.00\"), leaf(\"2.00\", 2)]}), D(\"5.00\"))\n\n    def test_discount(self):\n        b = {\"items\": [leaf(\"50.00\"), leaf(\"50.00\")], \"discount_percent\": 10}\n        self.assertEqual(bundle_price(b), D(\"90.00\"))\n\n    def test_discount_rounds_half_up(self):\n        b = {\"items\": [leaf(\"0.50\")], \"discount_percent\": 5}\n        self.assertEqual(bundle_price(b), D(\"0.48\"))\n\n    def test_nested_discounts(self):\n        inner = {\"items\": [leaf(\"100.00\")], \"discount_percent\": 20}\n        outer = {\"items\": [inner, leaf(\"20.00\")], \"discount_percent\": 50}\n        self.assertEqual(bundle_price(outer), D(\"50.00\"))\n\n    def test_empty_bundle(self):\n        self.assertEqual(bundle_price({\"items\": []}), D(\"0.00\"))\n        self.assertEqual(bundle_price({\"items\": [], \"discount_percent\": 10}), D(\"0.00\"))\n\n    def test_empty_nested_among_others(self):\n        outer = {\"items\": [{\"items\": [{\"items\": []}]}, leaf(\"3.00\")]}\n        self.assertEqual(bundle_price(outer), D(\"3.00\"))\n\n    def test_count_items(self):\n        outer = {\"items\": [leaf(\"1\", 3), {\"items\": [leaf(\"1\"), {\"items\": []}]}]}\n        self.assertEqual(count_items(outer), 4)\n        self.assertEqual(count_items({\"items\": []}), 0)\n\n    def test_depth(self):\n        self.assertEqual(depth(leaf(\"1\")), 0)\n        self.assertEqual(depth({\"items\": []}), 1)\n        self.assertEqual(depth({\"items\": [leaf(\"1\"), {\"items\": [leaf(\"2\")]}]}), 2)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Pricing for nested product bundles.\"\"\"\nfrom __future__ import annotations\n\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Any\n\nNode = dict[str, Any]\nCENT = Decimal(\"0.01\")\n\n\ndef bundle_price(node: Node) -> Decimal:\n    \"\"\"Total price of a leaf or bundle, applying bundle discounts.\"\"\"\n    if \"items\" not in node:\n        return node[\"price\"] * node.get(\"qty\", 1)\n    total = sum((bundle_price(child) for child in node[\"items\"]), Decimal(\"0\"))\n    discount = Decimal(node.get(\"discount_percent\", 0))\n    discounted = total * (Decimal(100) - discount) / Decimal(100)\n    return discounted.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef count_items(node: Node) -> int:\n    \"\"\"Total quantity of leaf items inside ``node``.\"\"\"\n    if \"items\" not in node:\n        return node.get(\"qty\", 1)\n    return sum(count_items(child) for child in node[\"items\"])\n\n\ndef depth(node: Node) -> int:\n    \"\"\"0 for a leaf, 1 for a bundle of leaves, and so on.\"\"\"\n    if \"items\" not in node:\n        return 0\n    return 1 + max((depth(child) for child in node[\"items\"]), default=0)\n"
  },
  {
   "id": "18-stock-reservations",
   "title": "Inventory reservations",
   "difficulty": "hard",
   "bugKind": "state not removed (pop vs lookup)",
   "description": "This module tracks stock levels with reservations. available(sku) is the stock on hand minus everything currently reserved for that SKU. reserve holds quantity under a reservation id (raising InsufficientStock if it exceeds what is available, ValueError for bad or duplicate requests). release cancels a reservation and returns its quantity, and commit turns a reservation into an actual stock decrease. Unknown reservation ids raise KeyError.",
   "buggy.py": "\"\"\"Stock levels with reservations that are later released or committed.\"\"\"\nfrom __future__ import annotations\n\n\nclass InsufficientStock(Exception):\n    \"\"\"Raised when a reservation asks for more than is available.\"\"\"\n\n\nclass Inventory:\n    \"\"\"On-hand quantities per SKU plus open reservations.\"\"\"\n\n    def __init__(self, on_hand: dict[str, int]) -> None:\n        self._on_hand = dict(on_hand)\n        self._reservations: dict[str, tuple[str, int]] = {}\n\n    def on_hand(self, sku: str) -> int:\n        \"\"\"Physical stock for the SKU.\"\"\"\n        return self._on_hand.get(sku, 0)\n\n    def available(self, sku: str) -> int:\n        \"\"\"Stock on hand minus open reservations for the SKU.\"\"\"\n        reserved = sum(q for s, q in self._reservations.values() if s == sku)\n        return self.on_hand(sku) - reserved\n\n    def reserve(self, res_id: str, sku: str, qty: int) -> None:\n        \"\"\"Hold ``qty`` units of ``sku`` under ``res_id``.\"\"\"\n        if qty <= 0:\n            raise ValueError(\"quantity must be positive\")\n        if res_id in self._reservations:\n            raise ValueError(\"duplicate reservation id\")\n        if qty > self.available(sku):\n            raise InsufficientStock(sku)\n        self._reservations[res_id] = (sku, qty)\n\n    def release(self, res_id: str) -> int:\n        \"\"\"Cancel a reservation; returns the quantity that was held.\"\"\"\n        _, qty = self._reservations.pop(res_id)\n        return qty\n\n    def commit(self, res_id: str) -> None:\n        \"\"\"Consume a reservation: the held units leave the stock.\"\"\"\n        sku, qty = self._reservations[res_id]\n        self._on_hand[sku] -= qty\n",
   "test_visible.py": "import unittest\nfrom solution import Inventory\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_commit_reduces_stock_once(self):\n        inv = Inventory({\"widget\": 10})\n        inv.reserve(\"r1\", \"widget\", 5)\n        inv.commit(\"r1\")\n        self.assertEqual(inv.available(\"widget\"), 5)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import Inventory, InsufficientStock\n\n\nclass HiddenTest(unittest.TestCase):\n    def setUp(self):\n        self.inv = Inventory({\"a\": 10, \"b\": 3})\n\n    def test_reserve_reduces_available_not_on_hand(self):\n        self.inv.reserve(\"r1\", \"a\", 4)\n        self.assertEqual(self.inv.available(\"a\"), 6)\n        self.assertEqual(self.inv.on_hand(\"a\"), 10)\n\n    def test_cannot_overreserve(self):\n        self.inv.reserve(\"r1\", \"a\", 7)\n        with self.assertRaises(InsufficientStock):\n            self.inv.reserve(\"r2\", \"a\", 4)\n        self.inv.reserve(\"r2\", \"a\", 3)\n        self.assertEqual(self.inv.available(\"a\"), 0)\n\n    def test_unknown_sku(self):\n        self.assertEqual(self.inv.available(\"zzz\"), 0)\n        with self.assertRaises(InsufficientStock):\n            self.inv.reserve(\"r1\", \"zzz\", 1)\n\n    def test_bad_requests(self):\n        with self.assertRaises(ValueError):\n            self.inv.reserve(\"r1\", \"a\", 0)\n        self.inv.reserve(\"r1\", \"a\", 1)\n        with self.assertRaises(ValueError):\n            self.inv.reserve(\"r1\", \"b\", 1)\n\n    def test_release_returns_quantity_and_frees_stock(self):\n        self.inv.reserve(\"r1\", \"a\", 4)\n        self.assertEqual(self.inv.release(\"r1\"), 4)\n        self.assertEqual(self.inv.available(\"a\"), 10)\n        self.assertEqual(self.inv.on_hand(\"a\"), 10)\n\n    def test_commit_decreases_on_hand(self):\n        self.inv.reserve(\"r1\", \"a\", 4)\n        self.inv.commit(\"r1\")\n        self.assertEqual(self.inv.on_hand(\"a\"), 6)\n        self.assertEqual(self.inv.available(\"a\"), 6)\n\n    def test_commit_twice_fails(self):\n        self.inv.reserve(\"r1\", \"a\", 4)\n        self.inv.commit(\"r1\")\n        with self.assertRaises(KeyError):\n            self.inv.commit(\"r1\")\n        self.assertEqual(self.inv.on_hand(\"a\"), 6)\n\n    def test_release_after_commit_fails(self):\n        self.inv.reserve(\"r1\", \"b\", 2)\n        self.inv.commit(\"r1\")\n        with self.assertRaises(KeyError):\n            self.inv.release(\"r1\")\n\n    def test_unknown_ids(self):\n        with self.assertRaises(KeyError):\n            self.inv.commit(\"nope\")\n        with self.assertRaises(KeyError):\n            self.inv.release(\"nope\")\n\n    def test_reservation_id_reusable_after_commit(self):\n        self.inv.reserve(\"r1\", \"b\", 2)\n        self.inv.commit(\"r1\")\n        self.inv.reserve(\"r1\", \"b\", 1)\n        self.assertEqual(self.inv.available(\"b\"), 0)\n\n    def test_other_sku_unaffected(self):\n        self.inv.reserve(\"r1\", \"a\", 4)\n        self.inv.commit(\"r1\")\n        self.assertEqual(self.inv.available(\"b\"), 3)\n\n    def test_constructor_copies_input(self):\n        stock = {\"a\": 1}\n        inv = Inventory(stock)\n        inv.reserve(\"r\", \"a\", 1)\n        inv.commit(\"r\")\n        self.assertEqual(stock, {\"a\": 1})\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Stock levels with reservations that are later released or committed.\"\"\"\nfrom __future__ import annotations\n\n\nclass InsufficientStock(Exception):\n    \"\"\"Raised when a reservation asks for more than is available.\"\"\"\n\n\nclass Inventory:\n    \"\"\"On-hand quantities per SKU plus open reservations.\"\"\"\n\n    def __init__(self, on_hand: dict[str, int]) -> None:\n        self._on_hand = dict(on_hand)\n        self._reservations: dict[str, tuple[str, int]] = {}\n\n    def on_hand(self, sku: str) -> int:\n        \"\"\"Physical stock for the SKU.\"\"\"\n        return self._on_hand.get(sku, 0)\n\n    def available(self, sku: str) -> int:\n        \"\"\"Stock on hand minus open reservations for the SKU.\"\"\"\n        reserved = sum(q for s, q in self._reservations.values() if s == sku)\n        return self.on_hand(sku) - reserved\n\n    def reserve(self, res_id: str, sku: str, qty: int) -> None:\n        \"\"\"Hold ``qty`` units of ``sku`` under ``res_id``.\"\"\"\n        if qty <= 0:\n            raise ValueError(\"quantity must be positive\")\n        if res_id in self._reservations:\n            raise ValueError(\"duplicate reservation id\")\n        if qty > self.available(sku):\n            raise InsufficientStock(sku)\n        self._reservations[res_id] = (sku, qty)\n\n    def release(self, res_id: str) -> int:\n        \"\"\"Cancel a reservation; returns the quantity that was held.\"\"\"\n        _, qty = self._reservations.pop(res_id)\n        return qty\n\n    def commit(self, res_id: str) -> None:\n        \"\"\"Consume a reservation: the held units leave the stock.\"\"\"\n        sku, qty = self._reservations.pop(res_id)\n        self._on_hand[sku] -= qty\n"
  },
  {
   "id": "19-subscription-proration",
   "title": "Subscription proration",
   "difficulty": "hard",
   "bugKind": "inconsistent day counting between helpers",
   "description": "This module prorates subscription charges in whole cents. Periods and service ranges are inclusive of both end dates. days_in_period counts the days in such a range. prorated_cents charges the share of the period price for the days from the service start through the period end, rounded half-up to whole cents. refund_cents returns the price for the days after a cancellation date through the period end.",
   "buggy.py": "\"\"\"Prorated subscription charges, in integer cents.\"\"\"\nfrom __future__ import annotations\n\nfrom datetime import date, timedelta\n\n\ndef days_in_period(start: date, end: date) -> int:\n    \"\"\"Number of days from ``start`` to ``end``, both inclusive.\"\"\"\n    if end < start:\n        raise ValueError(\"end before start\")\n    return (end - start).days + 1\n\n\ndef prorated_cents(price_cents: int, start_of_service: date,\n                   period_start: date, period_end: date) -> int:\n    \"\"\"Charge for service from ``start_of_service`` through ``period_end``.\n\n    The share is remaining days / total days of the billing period, rounded\n    half-up to whole cents.\n    \"\"\"\n    if not period_start <= start_of_service <= period_end:\n        raise ValueError(\"service start outside the billing period\")\n    remaining = (period_end - start_of_service).days\n    total = days_in_period(period_start, period_end)\n    return (price_cents * remaining * 2 + total) // (2 * total)\n\n\ndef refund_cents(price_cents: int, cancel_date: date,\n                 period_start: date, period_end: date) -> int:\n    \"\"\"Refund for the unused days after ``cancel_date`` (0 on the last day).\"\"\"\n    if not period_start <= cancel_date <= period_end:\n        raise ValueError(\"cancel date outside the billing period\")\n    if cancel_date == period_end:\n        return 0\n    first_unused = cancel_date + timedelta(days=1)\n    return prorated_cents(price_cents, first_unused, period_start, period_end)\n",
   "test_visible.py": "import unittest\nfrom datetime import date\nfrom solution import prorated_cents\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_second_half_of_month(self):\n        charge = prorated_cents(3000, date(2025, 11, 16), date(2025, 11, 1), date(2025, 11, 30))\n        self.assertEqual(charge, 1500)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom datetime import date\nfrom solution import days_in_period, prorated_cents, refund_cents\n\nSTART = date(2025, 11, 1)\nEND = date(2025, 11, 30)\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_days_in_period(self):\n        self.assertEqual(days_in_period(START, END), 30)\n        self.assertEqual(days_in_period(START, START), 1)\n\n    def test_days_in_period_invalid(self):\n        with self.assertRaises(ValueError):\n            days_in_period(END, START)\n\n    def test_full_period(self):\n        self.assertEqual(prorated_cents(3000, START, START, END), 3000)\n\n    def test_last_day_only(self):\n        self.assertEqual(prorated_cents(3000, END, START, END), 100)\n\n    def test_quarter(self):\n        self.assertEqual(prorated_cents(3000, date(2025, 11, 24), START, END), 700)\n\n    def test_rounding_half_up(self):\n        self.assertEqual(prorated_cents(1000, date(2025, 11, 29), START, END), 67)\n        self.assertEqual(prorated_cents(1050, date(2025, 11, 30), START, END), 35)\n        self.assertEqual(prorated_cents(15, date(2025, 11, 16), START, END), 8)\n\n    def test_other_period_length(self):\n        feb = (date(2025, 2, 1), date(2025, 2, 28))\n        self.assertEqual(prorated_cents(2800, date(2025, 2, 15), *feb), 1400)\n\n    def test_start_outside_period(self):\n        with self.assertRaises(ValueError):\n            prorated_cents(100, date(2025, 12, 1), START, END)\n        with self.assertRaises(ValueError):\n            prorated_cents(100, date(2025, 10, 31), START, END)\n\n    def test_refund_after_cancel(self):\n        self.assertEqual(refund_cents(3000, date(2025, 11, 15), START, END), 1500)\n\n    def test_refund_on_last_day_is_zero(self):\n        self.assertEqual(refund_cents(3000, END, START, END), 0)\n\n    def test_refund_day_before_end(self):\n        self.assertEqual(refund_cents(3000, date(2025, 11, 29), START, END), 100)\n\n    def test_charge_plus_refund_covers_price(self):\n        cancel = date(2025, 11, 10)\n        used = 3000 - refund_cents(3000, cancel, START, END)\n        self.assertEqual(used, 1000)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Prorated subscription charges, in integer cents.\"\"\"\nfrom __future__ import annotations\n\nfrom datetime import date, timedelta\n\n\ndef days_in_period(start: date, end: date) -> int:\n    \"\"\"Number of days from ``start`` to ``end``, both inclusive.\"\"\"\n    if end < start:\n        raise ValueError(\"end before start\")\n    return (end - start).days + 1\n\n\ndef prorated_cents(price_cents: int, start_of_service: date,\n                   period_start: date, period_end: date) -> int:\n    \"\"\"Charge for service from ``start_of_service`` through ``period_end``.\n\n    The share is remaining days / total days of the billing period, rounded\n    half-up to whole cents.\n    \"\"\"\n    if not period_start <= start_of_service <= period_end:\n        raise ValueError(\"service start outside the billing period\")\n    remaining = days_in_period(start_of_service, period_end)\n    total = days_in_period(period_start, period_end)\n    return (price_cents * remaining * 2 + total) // (2 * total)\n\n\ndef refund_cents(price_cents: int, cancel_date: date,\n                 period_start: date, period_end: date) -> int:\n    \"\"\"Refund for the unused days after ``cancel_date`` (0 on the last day).\"\"\"\n    if not period_start <= cancel_date <= period_end:\n        raise ValueError(\"cancel date outside the billing period\")\n    if cancel_date == period_end:\n        return 0\n    first_unused = cancel_date + timedelta(days=1)\n    return prorated_cents(price_cents, first_unused, period_start, period_end)\n"
  },
  {
   "id": "20-csv-line-parser",
   "title": "CSV-like line parser",
   "difficulty": "hard",
   "bugKind": "parser state/index advance",
   "description": "This module parses simple CSV-like text. parse_line splits one line on a separator, supports fields wrapped in double quotes (which may contain the separator) and a doubled quote inside a quoted field as an escaped quote character. parse_table treats the first non-blank line as the header and returns a list of dicts, raising ValueError when a row has a different number of fields than the header.",
   "buggy.py": "\"\"\"Parsing of simple CSV-like text.\"\"\"\nfrom __future__ import annotations\n\n\ndef parse_line(line: str, sep: str = \",\") -> list[str]:\n    \"\"\"Split one line into fields, honouring double-quoted fields.\n\n    Inside quotes the separator is literal and ``\"\"`` stands for one quote.\n    \"\"\"\n    fields: list[str] = []\n    buf: list[str] = []\n    in_quotes = False\n    i = 0\n    while i < len(line):\n        ch = line[i]\n        if in_quotes:\n            if ch == '\"':\n                if line[i + 1:i + 2] == '\"':\n                    buf.append('\"')\n                    i += 1\n                    continue\n                in_quotes = False\n            else:\n                buf.append(ch)\n        elif ch == '\"':\n            in_quotes = True\n        elif ch == sep:\n            fields.append(\"\".join(buf))\n            buf = []\n        else:\n            buf.append(ch)\n        i += 1\n    fields.append(\"\".join(buf))\n    return fields\n\n\ndef parse_table(text: str, sep: str = \",\") -> list[dict[str, str]]:\n    \"\"\"Parse text with a header line into a list of row dicts.\"\"\"\n    lines = [ln for ln in text.splitlines() if ln.strip()]\n    if not lines:\n        return []\n    header = parse_line(lines[0], sep)\n    rows = []\n    for ln in lines[1:]:\n        values = parse_line(ln, sep)\n        if len(values) != len(header):\n            raise ValueError(f\"expected {len(header)} fields, got {len(values)}\")\n        rows.append(dict(zip(header, values)))\n    return rows\n",
   "test_visible.py": "import unittest\nfrom solution import parse_line\n\n\nclass VisibleTest(unittest.TestCase):\n    def test_escaped_quotes_and_separator(self):\n        line = 'a,\"say \"\"hi\"\", ok\",c'\n        self.assertEqual(parse_line(line), [\"a\", 'say \"hi\", ok', \"c\"])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "test_hidden.py": "import unittest\nfrom solution import parse_line, parse_table\n\n\nclass HiddenTest(unittest.TestCase):\n    def test_plain(self):\n        self.assertEqual(parse_line(\"a,b,c\"), [\"a\", \"b\", \"c\"])\n\n    def test_empty_fields(self):\n        self.assertEqual(parse_line(\"a,,c,\"), [\"a\", \"\", \"c\", \"\"])\n        self.assertEqual(parse_line(\"\"), [\"\"])\n\n    def test_quoted_separator(self):\n        self.assertEqual(parse_line('\"a,b\",c'), [\"a,b\", \"c\"])\n\n    def test_escaped_quote_middle(self):\n        self.assertEqual(parse_line('\"a\"\"b\",c'), ['a\"b', \"c\"])\n\n    def test_escaped_quote_at_end(self):\n        self.assertEqual(parse_line('x,\"end \"\"\",y'), [\"x\", 'end \"', \"y\"])\n\n    def test_only_escaped_quote(self):\n        self.assertEqual(parse_line('\"\"\"\"'), ['\"'])\n\n    def test_two_escaped_quotes_in_a_row(self):\n        self.assertEqual(parse_line('\"a\"\"\"\"\",b'), ['a\"\"', \"b\"])\n\n    def test_empty_quoted_field(self):\n        self.assertEqual(parse_line('a,\"\",b'), [\"a\", \"\", \"b\"])\n\n    def test_custom_separator(self):\n        self.assertEqual(parse_line('a;\"b;c\";d', \";\"), [\"a\", \"b;c\", \"d\"])\n\n    def test_table(self):\n        text = 'name,note\\nann,\"hi, there\"\\n\\nbob,\"say \"\"yo\"\"\"\\n'\n        self.assertEqual(parse_table(text), [\n            {\"name\": \"ann\", \"note\": \"hi, there\"},\n            {\"name\": \"bob\", \"note\": 'say \"yo\"'},\n        ])\n\n    def test_table_errors_and_empty(self):\n        self.assertEqual(parse_table(\"\"), [])\n        with self.assertRaises(ValueError):\n            parse_table(\"a,b\\n1,2,3\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
   "referenceFix.py": "\"\"\"Parsing of simple CSV-like text.\"\"\"\nfrom __future__ import annotations\n\n\ndef parse_line(line: str, sep: str = \",\") -> list[str]:\n    \"\"\"Split one line into fields, honouring double-quoted fields.\n\n    Inside quotes the separator is literal and ``\"\"`` stands for one quote.\n    \"\"\"\n    fields: list[str] = []\n    buf: list[str] = []\n    in_quotes = False\n    i = 0\n    while i < len(line):\n        ch = line[i]\n        if in_quotes:\n            if ch == '\"':\n                if line[i + 1:i + 2] == '\"':\n                    buf.append('\"')\n                    i += 2\n                    continue\n                in_quotes = False\n            else:\n                buf.append(ch)\n        elif ch == '\"':\n            in_quotes = True\n        elif ch == sep:\n            fields.append(\"\".join(buf))\n            buf = []\n        else:\n            buf.append(ch)\n        i += 1\n    fields.append(\"\".join(buf))\n    return fields\n\n\ndef parse_table(text: str, sep: str = \",\") -> list[dict[str, str]]:\n    \"\"\"Parse text with a header line into a list of row dicts.\"\"\"\n    lines = [ln for ln in text.splitlines() if ln.strip()]\n    if not lines:\n        return []\n    header = parse_line(lines[0], sep)\n    rows = []\n    for ln in lines[1:]:\n        values = parse_line(ln, sep)\n        if len(values) != len(header):\n            raise ValueError(f\"expected {len(header)} fields, got {len(values)}\")\n        rows.append(dict(zip(header, values)))\n    return rows\n"
  }
 ]
}
