id
stringlengths
12
12
task_type
stringclasses
10 values
difficulty
stringclasses
4 values
prompt
stringlengths
227
393
response
stringclasses
32 values
metadata
dict
pygod_097501
bugfix
medium
Fix a subtle bug in a Python module used for event dispatching. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include type hints, must provide clear error messages, must avoid global state. Difficulty: medium. Support both Windows and POSIX paths correctly.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097502
bugfix
medium
Fix a subtle bug in a Python module used for rate limiting. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include docstrings, must be easy to extend, must provide clear error messages. Difficulty: medium. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097503
bugfix
hard
Fix a subtle bug in a Python module used for rate limiting. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include docstrings, must avoid global state. Difficulty: hard. Handle empty inputs and malformed records gracefully.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097504
bugfix
easy
Fix a subtle bug in a Python module used for event dispatching. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include docstrings, must be memory-efficient, must be easy to extend. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097505
bugfix
hard
Fix a subtle bug in a Python module used for file synchronization. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include docstrings, must include type hints, must include tests, must provide clear error messages. Difficulty: hard. Ensure the API is testable via dependency injection.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097506
bugfix
easy
Fix a subtle bug in a Python module used for CLI tooling. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must provide clear error messages, must avoid global state, must be streaming-friendly, must include tests. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097507
bugfix
easy
Fix a subtle bug in a Python module used for metrics aggregation. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include tests, must include type hints, must be memory-efficient, stdlib-only. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097508
bugfix
medium
Fix a subtle bug in a Python module used for data modeling. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: stdlib-only, must be memory-efficient, must include docstrings, must be streaming-friendly. Difficulty: medium. Guarantee deterministic output ordering.
Deliverable: implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097509
bugfix
medium
Fix a subtle bug in a Python module used for file synchronization. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include docstrings, stdlib-only, must be memory-efficient. Difficulty: medium. Provide helpful exceptions with actionable messages.
Deliverable: implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097510
bugfix
expert
Fix a subtle bug in a Python module used for ETL pipelines. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must be easy to extend, must include tests, must be streaming-friendly, must avoid global state. Difficulty: expert. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097511
bugfix
easy
Fix a subtle bug in a Python module used for parsing. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must be streaming-friendly, must provide clear error messages, must avoid global state. Difficulty: easy. Avoid quadratic behavior on large inputs.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097512
bugfix
easy
Fix a subtle bug in a Python module used for report generation. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include docstrings, must be streaming-friendly, must include tests. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097513
bugfix
expert
Fix a subtle bug in a Python module used for metrics aggregation. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must handle Windows paths safely, stdlib-only. Difficulty: expert. Provide helpful exceptions with actionable messages.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097514
bugfix
hard
Fix a subtle bug in a Python module used for parsing. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include type hints, must include docstrings, must be streaming-friendly. Difficulty: hard. Avoid quadratic behavior on large inputs.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097515
bugfix
expert
Fix a subtle bug in a Python module used for parsing. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include type hints, must be streaming-friendly, must include docstrings, must handle Windows paths safely. Difficulty: expert. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097516
bugfix
expert
Fix a subtle bug in a Python module used for ETL pipelines. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must be memory-efficient, must avoid global state, must include tests. Difficulty: expert. Handle empty inputs and malformed records gracefully.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097517
bugfix
expert
Fix a subtle bug in a Python module used for metrics aggregation. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must avoid global state, must include tests, must include docstrings, must include type hints. Difficulty: expert. Guarantee deterministic output ordering.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097518
bugfix
easy
Fix a subtle bug in a Python module used for time series. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include tests, must provide clear error messages, must avoid global state. Difficulty: easy. Handle empty inputs and malformed records gracefully.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097519
bugfix
hard
Fix a subtle bug in a Python module used for file synchronization. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must avoid global state, must be memory-efficient. Difficulty: hard. Handle empty inputs and malformed records gracefully.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097520
refactor
hard
Refactor a Python module used for data modeling into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must include docstrings, must include tests. Difficulty: hard. Ensure the API is testable via dependency injection.
Deliverable: implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097521
refactor
hard
Refactor a Python module used for rate limiting into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must handle Windows paths safely, must include type hints, must include docstrings, must be memory-efficient. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: production-ready reference solution. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097522
refactor
medium
Refactor a Python module used for event dispatching into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must include docstrings, must avoid global state, must handle Windows paths safely, must be memory-efficient. Difficulty: medium. Avoid quadratic behavior on large inputs.
Deliverable: API + reference implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097523
refactor
medium
Refactor a Python module used for validation into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be streaming-friendly, must handle Windows paths safely, must avoid global state, must include tests. Difficulty: medium. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097524
refactor
expert
Refactor a Python module used for caching layer into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be memory-efficient, must include docstrings. Difficulty: expert. Guarantee deterministic output ordering.
Deliverable: corrected code and verification tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097525
refactor
hard
Refactor a Python module used for caching layer into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must include docstrings, must be memory-efficient, must include tests. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097526
refactor
expert
Refactor a Python module used for metrics aggregation into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must include type hints, must be easy to extend, must include tests, stdlib-only. Difficulty: expert. Provide helpful exceptions with actionable messages.
Deliverable: production-ready reference solution. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097527
refactor
hard
Refactor a Python module used for telemetry ingestion into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: stdlib-only, must include type hints, must avoid global state, must provide clear error messages. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: production-ready reference solution. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097528
refactor
easy
Refactor a Python module used for report generation into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must provide clear error messages, must include tests. Difficulty: easy. Ensure the API is testable via dependency injection.
Deliverable: API + reference implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097529
refactor
hard
Refactor a Python module used for event dispatching into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must provide clear error messages, must be easy to extend, must include tests. Difficulty: hard. Ensure the API is testable via dependency injection.
Deliverable: implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097530
refactor
easy
Refactor a Python module used for telemetry ingestion into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be memory-efficient, must handle Windows paths safely, must include type hints, must provide clear error messages. Difficulty: easy. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097531
refactor
expert
Refactor a Python module used for caching layer into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be memory-efficient, stdlib-only. Difficulty: expert. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097532
refactor
easy
Refactor a Python module used for validation into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must avoid global state, must be streaming-friendly, stdlib-only. Difficulty: easy. Provide helpful exceptions with actionable messages.
Deliverable: implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097533
refactor
expert
Refactor a Python module used for event dispatching into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must include tests, must be streaming-friendly, must avoid global state, must handle Windows paths safely. Difficulty: expert. Avoid quadratic behavior on large inputs.
Deliverable: API + reference implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097534
refactor
easy
Refactor a Python module used for rate limiting into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must include docstrings, must include tests. Difficulty: easy. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "architecture", "clean-code" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097535
tests
easy
Write a thorough test suite for a Python component used for metrics aggregation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be easy to extend, must provide clear error messages, must avoid global state, stdlib-only. Difficulty: easy. Handle empty inputs and malformed records gracefully.
Deliverable: API + reference implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097536
tests
easy
Write a thorough test suite for a Python component used for validation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: stdlib-only, must be memory-efficient, must be easy to extend, must avoid global state. Difficulty: easy. Ensure the API is testable via dependency injection.
Deliverable: production-ready reference solution. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097537
tests
easy
Write a thorough test suite for a Python component used for configuration loading. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must include type hints, stdlib-only. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: corrected code and verification tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097538
tests
easy
Write a thorough test suite for a Python component used for telemetry ingestion. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must handle Windows paths safely, must avoid global state, must include tests. Difficulty: easy. Handle empty inputs and malformed records gracefully.
Deliverable: implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097539
tests
easy
Write a thorough test suite for a Python component used for validation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be memory-efficient, must include tests. Difficulty: easy. Handle empty inputs and malformed records gracefully.
Deliverable: API + reference implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097540
tests
hard
Write a thorough test suite for a Python component used for task scheduling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be memory-efficient, stdlib-only. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097541
tests
hard
Write a thorough test suite for a Python component used for validation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: stdlib-only, must be memory-efficient. Difficulty: hard. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097542
tests
expert
Write a thorough test suite for a Python component used for time series. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must handle Windows paths safely, must be streaming-friendly, must include docstrings. Difficulty: expert. Guarantee deterministic output ordering.
Deliverable: implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097543
tests
medium
Write a thorough test suite for a Python component used for task scheduling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must avoid global state, must provide clear error messages, stdlib-only, must include type hints. Difficulty: medium. Avoid quadratic behavior on large inputs.
Deliverable: implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097544
tests
expert
Write a thorough test suite for a Python component used for parsing. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must include type hints, stdlib-only. Difficulty: expert. Guarantee deterministic output ordering.
Deliverable: implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097545
tests
expert
Write a thorough test suite for a Python component used for event dispatching. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must include tests, must include docstrings, must be streaming-friendly, must handle Windows paths safely. Difficulty: expert. Avoid quadratic behavior on large inputs.
Deliverable: corrected code and verification tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097546
tests
hard
Write a thorough test suite for a Python component used for task scheduling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must handle Windows paths safely, must be memory-efficient. Difficulty: hard. Handle empty inputs and malformed records gracefully.
Deliverable: corrected code and verification tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097547
tests
hard
Write a thorough test suite for a Python component used for file synchronization. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be easy to extend, must provide clear error messages, must include docstrings, stdlib-only. Difficulty: hard. Support both Windows and POSIX paths correctly.
Deliverable: corrected code and verification tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097548
tests
medium
Write a thorough test suite for a Python component used for parsing. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must provide clear error messages, must avoid global state, must include type hints. Difficulty: medium. Include a small CLI example if relevant.
Deliverable: implementation + tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097549
tests
hard
Write a thorough test suite for a Python component used for validation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be easy to extend, must be streaming-friendly, must include docstrings, must include type hints. Difficulty: hard. Include a small CLI example if relevant.
Deliverable: corrected code and verification tests. ```python # tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats() import math import pytest def test_normalize_idempotent(module_under_test): x = " A\tB " assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x) def test_parse_lines_rejects_invalid(module_under_test): with pytest.raises(ValueError): module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type] def test_compute_stats_basic(module_under_test): data = [1, 2, 3, 4] s = module_under_test.compute_stats(data) assert s.count == 4 assert s.total == 10 assert math.isclose(s.mean, 2.5) ```
{ "tags": [ "python", "pytest_style", "unittesting" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097550
algorithms
expert
Design and implement an algorithm for data modeling. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must include type hints, must handle Windows paths safely. Difficulty: expert. Avoid quadratic behavior on large inputs.
Deliverable: production-ready reference solution. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097551
algorithms
expert
Design and implement an algorithm for event dispatching. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be streaming-friendly, stdlib-only, must include tests. Difficulty: expert. Handle empty inputs and malformed records gracefully.
Deliverable: corrected code and verification tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097552
algorithms
expert
Design and implement an algorithm for report generation. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: stdlib-only, must include type hints. Difficulty: expert. Include a small CLI example if relevant.
Deliverable: corrected code and verification tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097553
algorithms
hard
Design and implement an algorithm for configuration loading. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must include tests, must be easy to extend, must handle Windows paths safely. Difficulty: hard. Avoid quadratic behavior on large inputs.
Deliverable: implementation + tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097554
algorithms
expert
Design and implement an algorithm for validation. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must avoid global state, must be streaming-friendly, must include type hints, must be memory-efficient. Difficulty: expert. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097555
algorithms
medium
Design and implement an algorithm for data modeling. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be easy to extend, stdlib-only, must include tests, must include docstrings. Difficulty: medium. Guarantee deterministic output ordering.
Deliverable: corrected code and verification tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097556
algorithms
medium
Design and implement an algorithm for time series. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: stdlib-only, must include docstrings, must handle Windows paths safely, must provide clear error messages. Difficulty: medium. Handle empty inputs and malformed records gracefully.
Deliverable: corrected code and verification tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097557
algorithms
expert
Design and implement an algorithm for parsing. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be memory-efficient, must include type hints, must include docstrings. Difficulty: expert. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097558
algorithms
easy
Design and implement an algorithm for telemetry ingestion. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must provide clear error messages, must handle Windows paths safely, must avoid global state. Difficulty: easy. Avoid quadratic behavior on large inputs.
Deliverable: implementation + tests. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097559
algorithms
medium
Design and implement an algorithm for metrics aggregation. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be streaming-friendly, must include tests. Difficulty: medium. Handle empty inputs and malformed records gracefully.
Deliverable: production-ready reference solution. Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order. Complexity: sorting O(n log n); window maintenance O(n); memory O(k). ```python from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Iterable, List, Tuple @dataclass(frozen=True, slots=True) class Event: ts: int value: int def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]: if window_s < 0: raise ValueError("window_s must be >= 0") evs = sorted(events, key=lambda e: e.ts) q: deque[Event] = deque() s = 0 out: List[Tuple[int,int]] = [] for e in evs: q.append(e) s += e.value cutoff = e.ts - window_s while q and q[0].ts < cutoff: old = q.popleft() s -= old.value out.append((e.ts, s)) return out ``` ```python import pytest from module_under_test import Event, rolling_sum def test_rolling_sum(): ev = [Event(10,1), Event(11,2), Event(20,5)] assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)] ```
{ "tags": [ "python", "complexity", "correctness" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097560
typing
hard
Improve typing and robustness of a Python module used for telemetry ingestion. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include tests, must avoid global state, must include docstrings. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097561
typing
hard
Improve typing and robustness of a Python module used for CLI tooling. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include docstrings, stdlib-only, must avoid global state. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097562
typing
easy
Improve typing and robustness of a Python module used for log processing. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include type hints, must avoid global state, must handle Windows paths safely, stdlib-only. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097563
typing
hard
Improve typing and robustness of a Python module used for task scheduling. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include docstrings, must be streaming-friendly, stdlib-only, must include type hints. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097564
typing
easy
Improve typing and robustness of a Python module used for file synchronization. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must provide clear error messages, must include tests. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097565
typing
medium
Improve typing and robustness of a Python module used for log processing. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must be memory-efficient, must handle Windows paths safely. Difficulty: medium. Guarantee deterministic output ordering.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097566
typing
easy
Improve typing and robustness of a Python module used for time series. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include tests, must be memory-efficient. Difficulty: easy. Ensure the API is testable via dependency injection.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097567
typing
medium
Improve typing and robustness of a Python module used for telemetry ingestion. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must be memory-efficient, stdlib-only. Difficulty: medium. Support both Windows and POSIX paths correctly.
Deliverable: implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097568
typing
hard
Improve typing and robustness of a Python module used for ETL pipelines. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include type hints, must handle Windows paths safely. Difficulty: hard. Avoid quadratic behavior on large inputs.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097569
typing
hard
Improve typing and robustness of a Python module used for metrics aggregation. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must be memory-efficient, must be streaming-friendly, must be easy to extend. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from typing import Callable, Generic, Iterable, Protocol, TypeVar T = TypeVar("T") R = TypeVar("R") class Mapper(Protocol[T, R]): def __call__(self, x: T) -> R: ... @dataclass(frozen=True, slots=True) class Batch(Generic[T]): items: tuple[T, ...] def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]: return Batch(items=tuple(fn(x) for x in batch.items)) def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]: if size <= 0: raise ValueError("size must be > 0") buf: list[T] = [] for x in xs: buf.append(x) if len(buf) == size: yield Batch(items=tuple(buf)) buf.clear() if buf: yield Batch(items=tuple(buf)) ``` ```python import pytest from module_under_test import Batch, map_batch, chunked def test_map_batch(): b = Batch(items=(1,2,3)) assert map_batch(b, lambda x: x*2).items == (2,4,6) def test_chunked(): out = list(chunked([1,2,3,4,5], 2)) assert [b.items for b in out] == [(1,2),(3,4),(5,)] ```
{ "tags": [ "python", "mypy", "typing" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097570
performance
easy
Optimize a Python workflow for file synchronization. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be streaming-friendly, must include type hints, must include docstrings. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: implementation + tests. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097571
performance
hard
Optimize a Python workflow for CLI tooling. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must handle Windows paths safely, must provide clear error messages. Difficulty: hard. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097572
performance
hard
Optimize a Python workflow for parsing. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be easy to extend, must include type hints. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: production-ready reference solution. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097573
performance
hard
Optimize a Python workflow for rate limiting. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be memory-efficient, must include type hints. Difficulty: hard. Include a small CLI example if relevant.
Deliverable: corrected code and verification tests. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097574
performance
easy
Optimize a Python workflow for configuration loading. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be memory-efficient, must include tests. Difficulty: easy. Ensure the API is testable via dependency injection.
Deliverable: production-ready reference solution. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097575
performance
hard
Optimize a Python workflow for CLI tooling. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must handle Windows paths safely, must avoid global state, must include docstrings, must provide clear error messages. Difficulty: hard. Ensure the API is testable via dependency injection.
Deliverable: production-ready reference solution. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097576
performance
medium
Optimize a Python workflow for parsing. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must include type hints, must be easy to extend, must include docstrings. Difficulty: medium. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097577
performance
easy
Optimize a Python workflow for ETL pipelines. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must include type hints, must avoid global state, must handle Windows paths safely. Difficulty: easy. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. Strategy: - Avoid repeated parsing; precompile regex if needed; use local variables; stream processing. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable import time @dataclass(frozen=True, slots=True) class Stats: count: int total: int def compute_stats_stream(values: Iterable[int]) -> Stats: c = 0 t = 0 for v in values: c += 1 t += v return Stats(c, t) def bench(n: int = 1_000_00) -> float: data = range(n) t0 = time.perf_counter() _ = compute_stats_stream(data) return time.perf_counter() - t0 ``` ```python from module_under_test import bench def test_bench_runs_fast_enough(): # Sanity: should run quickly on typical machines; adjust threshold for CI. assert bench(50_000) < 0.5 ```
{ "tags": [ "python", "profiling", "optimization" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097578
concurrency
medium
Implement a concurrent Python solution for parsing. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must be easy to extend, must handle Windows paths safely. Difficulty: medium. Handle empty inputs and malformed records gracefully.
Deliverable: implementation + tests. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097579
concurrency
hard
Implement a concurrent Python solution for ETL pipelines. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must handle Windows paths safely, must include tests, must provide clear error messages, must avoid global state. Difficulty: hard. Avoid quadratic behavior on large inputs.
Deliverable: production-ready reference solution. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097580
concurrency
medium
Implement a concurrent Python solution for parsing. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must be easy to extend, must avoid global state. Difficulty: medium. Ensure the API is testable via dependency injection.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097581
concurrency
hard
Implement a concurrent Python solution for file synchronization. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must include tests, must be easy to extend, must avoid global state. Difficulty: hard. Handle empty inputs and malformed records gracefully.
Deliverable: implementation + tests. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097582
concurrency
medium
Implement a concurrent Python solution for data modeling. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must provide clear error messages, must avoid global state, must include docstrings. Difficulty: medium. Provide helpful exceptions with actionable messages.
Deliverable: production-ready reference solution. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097583
concurrency
easy
Implement a concurrent Python solution for caching layer. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: stdlib-only, must provide clear error messages, must be streaming-friendly, must avoid global state. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097584
concurrency
medium
Implement a concurrent Python solution for configuration loading. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must be streaming-friendly, must avoid global state, must provide clear error messages, must include docstrings. Difficulty: medium. Include a small CLI example if relevant.
Deliverable: API + reference implementation + tests. ```python from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Awaitable, Callable, Iterable, Optional @dataclass(frozen=True, slots=True) class JobResult: ok: bool value: Optional[int] error: Optional[str] async def run_bounded( factories: Iterable[Callable[[], Awaitable[int]]], *, limit: int = 10, timeout_s: float = 5.0, ) -> list[JobResult]: if limit <= 0: raise ValueError("limit must be > 0") sem = asyncio.Semaphore(limit) results: list[JobResult] = [] async def one(factory: Callable[[], Awaitable[int]]) -> None: async with sem: try: v = await asyncio.wait_for(factory(), timeout=timeout_s) results.append(JobResult(True, v, None)) except Exception as e: results.append(JobResult(False, None, str(e))) tasks = [asyncio.create_task(one(f)) for f in factories] try: await asyncio.gather(*tasks) finally: for t in tasks: if not t.done(): t.cancel() return results ``` ```python import asyncio import pytest from module_under_test import run_bounded @pytest.mark.asyncio async def test_run_bounded_collects(): async def work(x: int) -> int: await asyncio.sleep(0.01) return x fs = [(lambda i=i: work(i)) for i in range(30)] out = await run_bounded(fs, limit=5, timeout_s=1.0) assert len(out) == 30 assert all(r.ok for r in out) ```
{ "tags": [ "python", "asyncio", "threading" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097585
api_design
expert
Design a small, production-grade Python API for file synchronization. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must include docstrings, must be easy to extend, must include type hints. Difficulty: expert. Include a small CLI example if relevant.
Deliverable: implementation + tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097586
api_design
medium
Design a small, production-grade Python API for caching layer. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must include tests, stdlib-only. Difficulty: medium. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097587
api_design
easy
Design a small, production-grade Python API for task scheduling. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must include tests, must avoid global state, must be memory-efficient, stdlib-only. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: corrected code and verification tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097588
api_design
hard
Design a small, production-grade Python API for report generation. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must include type hints, must include tests, must include docstrings. Difficulty: hard. Support both Windows and POSIX paths correctly.
Deliverable: corrected code and verification tests. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097589
api_design
hard
Design a small, production-grade Python API for time series. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must handle Windows paths safely, must include tests, must include type hints, stdlib-only. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: production-ready reference solution. Architecture: - Public facade class coordinating concerns (parsing, validation, persistence) - Small pure functions for testability - No global state; dependency injection for filesystem I/O ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol, Iterable import json class Store(Protocol): def write_text(self, path: Path, data: str) -> None: ... class FSStore: def write_text(self, path: Path, data: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(data, encoding="utf-8") @dataclass(frozen=True, slots=True) class Item: name: str qty: int def parse_items(lines: Iterable[str]) -> list[Item]: out: list[Item] = [] for i, line in enumerate(lines, 1): s = line.strip() if not s: continue obj = json.loads(s) if not isinstance(obj, dict): raise ValueError(f"line {i}: expected object") name = obj.get("name") qty = obj.get("qty") if not isinstance(name, str) or not name: raise ValueError(f"line {i}: name must be str") if not isinstance(qty, int) or qty < 0: raise ValueError(f"line {i}: qty must be non-negative int") out.append(Item(name, qty)) return out class InventoryWriter: def __init__(self, base_dir: Path, store: Store | None = None) -> None: self._base = base_dir self._store: Store = store or FSStore() def write(self, rel_path: str, items: list[Item]) -> Path: dst = (self._base / rel_path).resolve() base = self._base.resolve() if dst != base and base not in dst.parents: raise ValueError("unsafe path traversal") payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False) self._store.write_text(dst, payload) return dst ``` ```python import json from pathlib import Path import pytest from module_under_test import InventoryWriter, parse_items def test_parse_items_valid(): lines = [json.dumps({"name":"x","qty":1})] assert parse_items(lines)[0].name == "x" def test_writer_blocks_traversal(tmp_path: Path): w = InventoryWriter(tmp_path) with pytest.raises(ValueError): w.write("../evil.json", []) ```
{ "tags": [ "python", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097590
packaging
medium
Create a small, production-ready Python package for time series. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must handle Windows paths safely, must avoid global state, must be streaming-friendly. Difficulty: medium. Provide helpful exceptions with actionable messages.
Deliverable: implementation + tests. Package layout: - mypkg/core.py - mypkg/cli.py - pyproject.toml ```python # mypkg/core.py from __future__ import annotations from dataclasses import dataclass from typing import Iterable import logging log = logging.getLogger(__name__) @dataclass(frozen=True, slots=True) class Result: total: int count: int def aggregate(values: Iterable[int]) -> Result: total = 0 count = 0 for v in values: if not isinstance(v, int): raise TypeError("values must be ints") total += v count += 1 log.debug("aggregate count=%s total=%s", count, total) return Result(total, count) ``` ```python # mypkg/cli.py from __future__ import annotations import argparse import logging import sys from .core import aggregate def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="mypkg") p.add_argument("--log-level", default="WARNING") args = p.parse_args(argv) logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING)) data: list[int] = [] for line in sys.stdin: line = line.strip() if line: data.append(int(line)) r = aggregate(data) print(f"count={r.count} total={r.total}") return 0 ``` ```toml # pyproject.toml [project] name = "mypkg" version = "0.1.0" requires-python = ">=3.10" [project.scripts] mypkg = "mypkg.cli:main" ```
{ "tags": [ "python", "cli", "pyproject" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097591
packaging
medium
Create a small, production-ready Python package for task scheduling. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must be easy to extend, must be memory-efficient, must handle Windows paths safely, must include docstrings. Difficulty: medium. Handle empty inputs and malformed records gracefully.
Deliverable: implementation + tests. Package layout: - mypkg/core.py - mypkg/cli.py - pyproject.toml ```python # mypkg/core.py from __future__ import annotations from dataclasses import dataclass from typing import Iterable import logging log = logging.getLogger(__name__) @dataclass(frozen=True, slots=True) class Result: total: int count: int def aggregate(values: Iterable[int]) -> Result: total = 0 count = 0 for v in values: if not isinstance(v, int): raise TypeError("values must be ints") total += v count += 1 log.debug("aggregate count=%s total=%s", count, total) return Result(total, count) ``` ```python # mypkg/cli.py from __future__ import annotations import argparse import logging import sys from .core import aggregate def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="mypkg") p.add_argument("--log-level", default="WARNING") args = p.parse_args(argv) logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING)) data: list[int] = [] for line in sys.stdin: line = line.strip() if line: data.append(int(line)) r = aggregate(data) print(f"count={r.count} total={r.total}") return 0 ``` ```toml # pyproject.toml [project] name = "mypkg" version = "0.1.0" requires-python = ">=3.10" [project.scripts] mypkg = "mypkg.cli:main" ```
{ "tags": [ "python", "cli", "pyproject" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097592
packaging
hard
Create a small, production-ready Python package for data modeling. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must include type hints, must be memory-efficient. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: API + reference implementation + tests. Package layout: - mypkg/core.py - mypkg/cli.py - pyproject.toml ```python # mypkg/core.py from __future__ import annotations from dataclasses import dataclass from typing import Iterable import logging log = logging.getLogger(__name__) @dataclass(frozen=True, slots=True) class Result: total: int count: int def aggregate(values: Iterable[int]) -> Result: total = 0 count = 0 for v in values: if not isinstance(v, int): raise TypeError("values must be ints") total += v count += 1 log.debug("aggregate count=%s total=%s", count, total) return Result(total, count) ``` ```python # mypkg/cli.py from __future__ import annotations import argparse import logging import sys from .core import aggregate def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="mypkg") p.add_argument("--log-level", default="WARNING") args = p.parse_args(argv) logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING)) data: list[int] = [] for line in sys.stdin: line = line.strip() if line: data.append(int(line)) r = aggregate(data) print(f"count={r.count} total={r.total}") return 0 ``` ```toml # pyproject.toml [project] name = "mypkg" version = "0.1.0" requires-python = ">=3.10" [project.scripts] mypkg = "mypkg.cli:main" ```
{ "tags": [ "python", "cli", "pyproject" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097593
packaging
easy
Create a small, production-ready Python package for data modeling. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: stdlib-only, must handle Windows paths safely, must be easy to extend, must include docstrings. Difficulty: easy. Support both Windows and POSIX paths correctly.
Deliverable: corrected code and verification tests. Package layout: - mypkg/core.py - mypkg/cli.py - pyproject.toml ```python # mypkg/core.py from __future__ import annotations from dataclasses import dataclass from typing import Iterable import logging log = logging.getLogger(__name__) @dataclass(frozen=True, slots=True) class Result: total: int count: int def aggregate(values: Iterable[int]) -> Result: total = 0 count = 0 for v in values: if not isinstance(v, int): raise TypeError("values must be ints") total += v count += 1 log.debug("aggregate count=%s total=%s", count, total) return Result(total, count) ``` ```python # mypkg/cli.py from __future__ import annotations import argparse import logging import sys from .core import aggregate def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="mypkg") p.add_argument("--log-level", default="WARNING") args = p.parse_args(argv) logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING)) data: list[int] = [] for line in sys.stdin: line = line.strip() if line: data.append(int(line)) r = aggregate(data) print(f"count={r.count} total={r.total}") return 0 ``` ```toml # pyproject.toml [project] name = "mypkg" version = "0.1.0" requires-python = ">=3.10" [project.scripts] mypkg = "mypkg.cli:main" ```
{ "tags": [ "python", "cli", "pyproject" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097594
packaging
medium
Create a small, production-ready Python package for report generation. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must include docstrings, must avoid global state, stdlib-only. Difficulty: medium. Handle empty inputs and malformed records gracefully.
Deliverable: production-ready reference solution. Package layout: - mypkg/core.py - mypkg/cli.py - pyproject.toml ```python # mypkg/core.py from __future__ import annotations from dataclasses import dataclass from typing import Iterable import logging log = logging.getLogger(__name__) @dataclass(frozen=True, slots=True) class Result: total: int count: int def aggregate(values: Iterable[int]) -> Result: total = 0 count = 0 for v in values: if not isinstance(v, int): raise TypeError("values must be ints") total += v count += 1 log.debug("aggregate count=%s total=%s", count, total) return Result(total, count) ``` ```python # mypkg/cli.py from __future__ import annotations import argparse import logging import sys from .core import aggregate def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="mypkg") p.add_argument("--log-level", default="WARNING") args = p.parse_args(argv) logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING)) data: list[int] = [] for line in sys.stdin: line = line.strip() if line: data.append(int(line)) r = aggregate(data) print(f"count={r.count} total={r.total}") return 0 ``` ```toml # pyproject.toml [project] name = "mypkg" version = "0.1.0" requires-python = ">=3.10" [project.scripts] mypkg = "mypkg.cli:main" ```
{ "tags": [ "python", "cli", "pyproject" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097595
security_safe
hard
Write secure, defensive Python code for time series. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must include type hints, must be memory-efficient. Difficulty: hard. Guarantee deterministic output ordering.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "security", "validation" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097596
security_safe
hard
Write secure, defensive Python code for rate limiting. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must be streaming-friendly, must include type hints, must be memory-efficient. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "security", "validation" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097597
security_safe
hard
Write secure, defensive Python code for file synchronization. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must include type hints, must include docstrings, must include tests. Difficulty: hard. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "security", "validation" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097598
security_safe
medium
Write secure, defensive Python code for data modeling. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must provide clear error messages, must include tests. Difficulty: medium. Support both Windows and POSIX paths correctly.
Deliverable: implementation + tests. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "security", "validation" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097599
security_safe
easy
Write secure, defensive Python code for configuration loading. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must be easy to extend, must handle Windows paths safely, stdlib-only, must include tests. Difficulty: easy. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "security", "validation" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097600
bugfix
expert
Fix a subtle bug in a Python module used for telemetry ingestion. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must be streaming-friendly, must include tests, must be easy to extend, stdlib-only. Difficulty: expert. Include a small CLI example if relevant.
Deliverable: production-ready reference solution. ```python from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable import json class ValidationError(ValueError): """Raised when input validation fails.""" def safe_join(base: Path, *parts: str) -> Path: """Join paths while preventing traversal outside base.""" b = base.resolve() p = (b / Path(*parts)).resolve() if p != b and b not in p.parents: raise ValidationError(f"unsafe path: {p}") return p @dataclass(frozen=True, slots=True) class Record: key: str value: int def parse_jsonl(lines: Iterable[str]) -> list[Record]: out: list[Record] = [] for idx, line in enumerate(lines, 1): s = line.strip() if not s: continue try: obj = json.loads(s) except json.JSONDecodeError as e: raise ValidationError(f"line {idx}: invalid json") from e if not isinstance(obj, dict): raise ValidationError(f"line {idx}: expected object") key = obj.get("key") val = obj.get("value") if not isinstance(key, str) or not key: raise ValidationError(f"line {idx}: key must be non-empty str") if not isinstance(val, int): raise ValidationError(f"line {idx}: value must be int") out.append(Record(key, val)) return out def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path: base.mkdir(parents=True, exist_ok=True) dst = safe_join(base, rel) dst.parent.mkdir(parents=True, exist_ok=True) with dst.open("w", encoding="utf-8", newline="\n") as f: for r in records: f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n") return dst ``` ```python # tests (pytest-style) import json from pathlib import Path import pytest from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl def test_parse_ok(): lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})] assert parse_jsonl(lines) == [Record("a",1), Record("b",2)] def test_parse_rejects_bad_json(): with pytest.raises(ValidationError): parse_jsonl(["{not json}"]) def test_safe_join_blocks_traversal(tmp_path: Path): with pytest.raises(ValidationError): write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)]) ```
{ "tags": [ "python", "debugging", "tests" ], "has_code": true, "requires_thinking": true, "seed": 1337 }