{
 "edition": "coding-models/2026-11",
 "product": "qwen4-max",
 "productName": "Qwen4-Max",
 "openRouterModel": "qwen/qwen4-max",
 "priceAtTestUsdPerMillionTokens": {
  "input": 1.425,
  "output": 4.275
 },
 "testedOn": "2026-11-24",
 "place": null,
 "pick": null,
 "result": {
  "passedRuns": 40,
  "runs": 40,
  "scorePercent": 100.0,
  "tasksFailedInEveryRound": [],
  "totalCostUsd": 0.0773,
  "costPerPassedRunUsd": 0.00193,
  "medianLatencySeconds": 4.09,
  "medianCompletionTokens": 400,
  "repliesCutOffAtTokenLimit": 0,
  "callsWithoutReply": 0,
  "providers": [
   "Alibaba"
  ]
 },
 "method": "https://appfor.ai/rankings-evidence/2026-11-coding-models/README.txt",
 "tasks": "https://appfor.ai/rankings-evidence/2026-11-coding-models/tasks.json",
 "runs": [
  {
   "task": "01-invoice-vat",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.881,
   "finishReason": "stop",
   "promptTokens": 544,
   "completionTokens": 319,
   "reasoningTokens": 21,
   "costUsd": 0.001445805,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "02-slugify",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.126,
   "finishReason": "stop",
   "promptTokens": 561,
   "completionTokens": 355,
   "reasoningTokens": 17,
   "costUsd": 0.00162393,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "03-pagination",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.179,
   "finishReason": "stop",
   "promptTokens": 552,
   "completionTokens": 322,
   "reasoningTokens": 12,
   "costUsd": 0.00147003,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "04-shipping-cost",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.349,
   "finishReason": "stop",
   "promptTokens": 576,
   "completionTokens": 378,
   "reasoningTokens": 40,
   "costUsd": 0.00174363,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "05-leaderboard",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.637,
   "finishReason": "stop",
   "promptTokens": 632,
   "completionTokens": 376,
   "reasoningTokens": 29,
   "costUsd": 0.00181488,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "06-ticket-tags",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.229,
   "finishReason": "stop",
   "promptTokens": 529,
   "completionTokens": 318,
   "reasoningTokens": 9,
   "costUsd": 0.001420155,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "07-latency-stats",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.289,
   "finishReason": "stop",
   "promptTokens": 521,
   "completionTokens": 304,
   "reasoningTokens": 10,
   "costUsd": 0.001348905,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "08-cart-summary",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.928,
   "finishReason": "stop",
   "promptTokens": 557,
   "completionTokens": 494,
   "reasoningTokens": 157,
   "costUsd": 0.002212455,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "09-version-compare",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.973,
   "finishReason": "stop",
   "promptTokens": 639,
   "completionTokens": 462,
   "reasoningTokens": 82,
   "costUsd": 0.002192505,
   "reply": "```python\n\"\"\"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(part) for part 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```",
   "extractedSolution": "\"\"\"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(part) for part 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",
   "errors": []
  },
  {
   "task": "10-token-bucket",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.807,
   "finishReason": "stop",
   "promptTokens": 760,
   "completionTokens": 490,
   "reasoningTokens": 17,
   "costUsd": 0.00248463,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "11-retry-backoff",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.467,
   "finishReason": "stop",
   "promptTokens": 602,
   "completionTokens": 363,
   "reasoningTokens": 13,
   "costUsd": 0.001716555,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "12-room-bookings",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 6.263,
   "finishReason": "stop",
   "promptTokens": 730,
   "completionTokens": 596,
   "reasoningTokens": 168,
   "costUsd": 0.00289503,
   "reply": "```python\n\"\"\"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    bookings = list(bookings)\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```",
   "extractedSolution": "\"\"\"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    bookings = list(bookings)\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",
   "errors": []
  },
  {
   "task": "13-layered-config",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.707,
   "finishReason": "stop",
   "promptTokens": 532,
   "completionTokens": 332,
   "reasoningTokens": 59,
   "costUsd": 0.00148428,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "14-password-policy",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.853,
   "finishReason": "stop",
   "promptTokens": 615,
   "completionTokens": 418,
   "reasoningTokens": 44,
   "costUsd": 0.001970205,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "15-normalize-weights",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.047,
   "finishReason": "stop",
   "promptTokens": 513,
   "completionTokens": 273,
   "reasoningTokens": 9,
   "costUsd": 0.00120498,
   "reply": "```python\n\"\"\"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    vals = list(values)\n    total = sum(vals)\n    if total == 0:\n        raise ValueError(\"weights must not sum to zero\")\n    return [v / total for v in vals]\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```",
   "extractedSolution": "\"\"\"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    vals = list(values)\n    total = sum(vals)\n    if total == 0:\n        raise ValueError(\"weights must not sum to zero\")\n    return [v / total for v in vals]\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",
   "errors": []
  },
  {
   "task": "16-ellipsize",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.663,
   "finishReason": "stop",
   "promptTokens": 527,
   "completionTokens": 458,
   "reasoningTokens": 161,
   "costUsd": 0.002015805,
   "reply": "```python\n\"\"\"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 - len(ELLIPSIS)] + ELLIPSIS\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:] if tail else \"\")\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```",
   "extractedSolution": "\"\"\"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 - len(ELLIPSIS)] + ELLIPSIS\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:] if tail else \"\")\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",
   "errors": []
  },
  {
   "task": "17-bundle-pricing",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.982,
   "finishReason": "stop",
   "promptTokens": 590,
   "completionTokens": 486,
   "reasoningTokens": 180,
   "costUsd": 0.00222528,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "18-stock-reservations",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.614,
   "finishReason": "stop",
   "promptTokens": 685,
   "completionTokens": 486,
   "reasoningTokens": 69,
   "costUsd": 0.002360655,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "19-subscription-proration",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 5.041,
   "finishReason": "stop",
   "promptTokens": 672,
   "completionTokens": 492,
   "reasoningTokens": 122,
   "costUsd": 0.00236778,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "20-csv-line-parser",
   "round": 1,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 5.182,
   "finishReason": "stop",
   "promptTokens": 649,
   "completionTokens": 538,
   "reasoningTokens": 148,
   "costUsd": 0.002531655,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "01-invoice-vat",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.626,
   "finishReason": "stop",
   "promptTokens": 544,
   "completionTokens": 306,
   "reasoningTokens": 8,
   "costUsd": 0.00139023,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "02-slugify",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.994,
   "finishReason": "stop",
   "promptTokens": 561,
   "completionTokens": 387,
   "reasoningTokens": 49,
   "costUsd": 0.00176073,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "03-pagination",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.494,
   "finishReason": "stop",
   "promptTokens": 552,
   "completionTokens": 329,
   "reasoningTokens": 19,
   "costUsd": 0.001499955,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "04-shipping-cost",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.7,
   "finishReason": "stop",
   "promptTokens": 576,
   "completionTokens": 358,
   "reasoningTokens": 20,
   "costUsd": 0.00165813,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "05-leaderboard",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.417,
   "finishReason": "stop",
   "promptTokens": 632,
   "completionTokens": 376,
   "reasoningTokens": 29,
   "costUsd": 0.00181488,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "06-ticket-tags",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.083,
   "finishReason": "stop",
   "promptTokens": 529,
   "completionTokens": 337,
   "reasoningTokens": 28,
   "costUsd": 0.00150138,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "07-latency-stats",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.196,
   "finishReason": "stop",
   "promptTokens": 521,
   "completionTokens": 301,
   "reasoningTokens": 7,
   "costUsd": 0.00133608,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "08-cart-summary",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.728,
   "finishReason": "stop",
   "promptTokens": 557,
   "completionTokens": 413,
   "reasoningTokens": 64,
   "costUsd": 0.00186618,
   "reply": "```python\n\"\"\"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 {\n            \"count\": 0,\n            \"total\": ZERO,\n            \"average\": ZERO,\n            \"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```",
   "extractedSolution": "\"\"\"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 {\n            \"count\": 0,\n            \"total\": ZERO,\n            \"average\": ZERO,\n            \"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",
   "errors": []
  },
  {
   "task": "09-version-compare",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.614,
   "finishReason": "stop",
   "promptTokens": 639,
   "completionTokens": 453,
   "reasoningTokens": 73,
   "costUsd": 0.00215403,
   "reply": "```python\n\"\"\"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(part) for part 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```",
   "extractedSolution": "\"\"\"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(part) for part 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",
   "errors": []
  },
  {
   "task": "10-token-bucket",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.232,
   "finishReason": "stop",
   "promptTokens": 760,
   "completionTokens": 490,
   "reasoningTokens": 17,
   "costUsd": 0.00248463,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "11-retry-backoff",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.374,
   "finishReason": "stop",
   "promptTokens": 602,
   "completionTokens": 363,
   "reasoningTokens": 13,
   "costUsd": 0.001716555,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "12-room-bookings",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 6.572,
   "finishReason": "stop",
   "promptTokens": 730,
   "completionTokens": 650,
   "reasoningTokens": 222,
   "costUsd": 0.00312588,
   "reply": "```python\n\"\"\"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    bookings = list(bookings)\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```",
   "extractedSolution": "\"\"\"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    bookings = list(bookings)\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",
   "errors": []
  },
  {
   "task": "13-layered-config",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.867,
   "finishReason": "stop",
   "promptTokens": 532,
   "completionTokens": 370,
   "reasoningTokens": 97,
   "costUsd": 0.00164673,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "14-password-policy",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.729,
   "finishReason": "stop",
   "promptTokens": 615,
   "completionTokens": 414,
   "reasoningTokens": 40,
   "costUsd": 0.001953105,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "15-normalize-weights",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 3.428,
   "finishReason": "stop",
   "promptTokens": 513,
   "completionTokens": 298,
   "reasoningTokens": 34,
   "costUsd": 0.001311855,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "16-ellipsize",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 5.427,
   "finishReason": "stop",
   "promptTokens": 527,
   "completionTokens": 483,
   "reasoningTokens": 191,
   "costUsd": 0.00212268,
   "reply": "```python\n\"\"\"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 - len(ELLIPSIS)] + ELLIPSIS\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```",
   "extractedSolution": "\"\"\"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 - len(ELLIPSIS)] + ELLIPSIS\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",
   "errors": []
  },
  {
   "task": "17-bundle-pricing",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.524,
   "finishReason": "stop",
   "promptTokens": 590,
   "completionTokens": 444,
   "reasoningTokens": 138,
   "costUsd": 0.00204573,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "18-stock-reservations",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 5.04,
   "finishReason": "stop",
   "promptTokens": 685,
   "completionTokens": 460,
   "reasoningTokens": 43,
   "costUsd": 0.002249505,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "19-subscription-proration",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 4.538,
   "finishReason": "stop",
   "promptTokens": 672,
   "completionTokens": 483,
   "reasoningTokens": 113,
   "costUsd": 0.002329305,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  },
  {
   "task": "20-csv-line-parser",
   "round": 2,
   "passed": true,
   "testResult": "OK",
   "status": "ok",
   "provider": "Alibaba",
   "latencySeconds": 6.657,
   "finishReason": "stop",
   "promptTokens": 649,
   "completionTokens": 607,
   "reasoningTokens": 217,
   "costUsd": 0.00282663,
   "reply": "```python\n\"\"\"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```",
   "extractedSolution": "\"\"\"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",
   "errors": []
  }
 ]
}
