id
stringlengths
12
12
task_type
stringclasses
10 values
difficulty
stringclasses
4 values
prompt
stringlengths
227
393
response
stringclasses
32 values
metadata
dict
pygod_097901
bugfix
easy
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: must avoid global state, must include type hints, stdlib-only, must be memory-efficient. Difficulty: easy. Support both Windows and POSIX paths correctly.
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_097902
bugfix
expert
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: must include tests, must avoid global state. 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_097903
bugfix
expert
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 be streaming-friendly, must be easy to extend, must provide clear error messages. Difficulty: expert. 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_097904
bugfix
expert
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: must be memory-efficient, must include docstrings, must include tests. Difficulty: expert. Support both Windows and POSIX paths correctly.
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_097905
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 be streaming-friendly, must avoid global state, must provide clear error messages, must be easy to extend. Difficulty: medium. 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_097906
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: stdlib-only, must avoid global state. Difficulty: easy. Handle empty inputs and malformed records gracefully.
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_097907
bugfix
easy
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 include docstrings, must include type hints. Difficulty: easy. 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", "debugging", "tests" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097908
bugfix
expert
Fix a subtle bug in a Python module used for validation. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include tests, must be easy to extend, must handle Windows paths safely. 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_097909
bugfix
hard
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 include docstrings, stdlib-only, must be easy to extend. Difficulty: hard. 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": true, "seed": 1337 }
pygod_097910
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 tests, must include docstrings. Difficulty: easy. Ensure the API is testable via dependency injection.
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_097911
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 include tests, must include docstrings, must be easy to extend, must be memory-efficient. Difficulty: easy. Support both Windows and POSIX paths correctly.
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_097912
bugfix
hard
Fix a subtle bug in a Python module used for log processing. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must be memory-efficient, must include tests, must handle Windows paths safely, must include type hints. Difficulty: hard. Ensure the API is testable via dependency injection.
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_097913
bugfix
expert
Fix a subtle bug in a Python module used for task scheduling. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must include type hints, stdlib-only, must avoid global state. Difficulty: expert. 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_097914
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 be memory-efficient, must avoid global state, must include docstrings. Difficulty: expert. Ensure the API is testable via dependency injection.
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_097915
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 tests, must be easy to extend, must provide clear error messages. Difficulty: expert. 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": true, "seed": 1337 }
pygod_097916
bugfix
medium
Fix a subtle bug in a Python module used for task scheduling. Requirements: explain root cause briefly, provide corrected code, and add regression tests. Constraints: must be easy to extend, must provide clear error messages. Difficulty: medium. Handle empty inputs and malformed records gracefully.
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_097917
bugfix
hard
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 avoid global state, must be streaming-friendly, must be easy to extend. Difficulty: hard. Handle empty inputs and malformed records gracefully.
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_097918
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 include tests, stdlib-only, must include docstrings. Difficulty: easy. Support both Windows and POSIX paths correctly.
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_097919
bugfix
easy
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 be streaming-friendly, must include tests. Difficulty: easy. Handle empty inputs and malformed records gracefully.
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_097920
refactor
expert
Refactor a Python module used for time series 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 memory-efficient, stdlib-only, must be easy to extend. Difficulty: expert. Avoid quadratic behavior on large inputs.
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_097921
refactor
expert
Refactor a Python module used for parsing 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 tests. Difficulty: expert. 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", "architecture", "clean-code" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097922
refactor
easy
Refactor a Python module used for CLI tooling into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be easy to extend, must be streaming-friendly, must avoid global state, 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_097923
refactor
medium
Refactor a Python module used for CLI tooling 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 memory-efficient. Difficulty: medium. 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_097924
refactor
medium
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: stdlib-only, must provide clear error messages. Difficulty: medium. Ensure the API is testable via dependency injection.
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_097925
refactor
expert
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 include type hints, stdlib-only, must avoid global state. Difficulty: expert. Avoid quadratic behavior on large inputs.
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_097926
refactor
hard
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 avoid global state, must provide clear error messages, stdlib-only. Difficulty: hard. 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_097927
refactor
expert
Refactor a Python module used for file synchronization 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 type hints. Difficulty: expert. 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_097928
refactor
medium
Refactor a Python module used for parsing 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 memory-efficient. Difficulty: medium. Support both Windows and POSIX paths correctly.
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_097929
refactor
medium
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 streaming-friendly, must provide clear error messages, must include tests, must include type hints. Difficulty: medium. Ensure the API is testable via dependency injection.
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_097930
refactor
easy
Refactor a Python module used for log processing into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be easy to extend, must include docstrings, must handle Windows paths safely. Difficulty: easy. Handle empty inputs and malformed records gracefully.
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": false, "seed": 1337 }
pygod_097931
refactor
medium
Refactor a Python module used for configuration loading into a clean, extensible design. Requirements: outline the new architecture briefly, then provide the refactored code and tests. Constraints: must be easy to extend, must include tests. Difficulty: medium. Handle empty inputs and malformed records gracefully.
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": false, "seed": 1337 }
pygod_097932
refactor
hard
Refactor a Python module used for file synchronization 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 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_097933
refactor
expert
Refactor a Python module used for task scheduling 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. Difficulty: expert. 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_097934
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 memory-efficient, must include tests, must include docstrings. Difficulty: medium. Handle empty inputs and malformed records gracefully.
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_097935
tests
hard
Write a thorough test suite for a Python component used for data modeling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must avoid global state, must include tests, stdlib-only. Difficulty: hard. 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": true, "seed": 1337 }
pygod_097936
tests
medium
Write a thorough test suite for a Python component used for ETL pipelines. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must include tests, must be memory-efficient, must handle Windows paths safely. Difficulty: medium. Include a small CLI example if relevant.
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_097937
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 provide clear error messages, must be memory-efficient. Difficulty: expert. Ensure the API is testable via dependency injection.
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_097938
tests
easy
Write a thorough test suite for a Python component used for report generation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must handle Windows paths safely, must avoid global state, must be memory-efficient, must include type hints. 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_097939
tests
expert
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 be easy to extend, must provide clear error messages, stdlib-only. Difficulty: expert. 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": true, "seed": 1337 }
pygod_097940
tests
medium
Write a thorough test suite for a Python component used for ETL pipelines. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must avoid global state, must be streaming-friendly, must include docstrings. Difficulty: medium. Avoid quadratic behavior on large inputs.
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_097941
tests
medium
Write a thorough test suite for a Python component used for event dispatching. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be easy to extend, must include type hints. Difficulty: medium. Guarantee deterministic output ordering.
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_097942
tests
easy
Write a thorough test suite for a Python component used for data modeling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: stdlib-only, must avoid global state, must provide clear error messages. Difficulty: easy. 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": false, "seed": 1337 }
pygod_097943
tests
hard
Write a thorough test suite for a Python component used for data modeling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must include docstrings, must be easy to extend. Difficulty: hard. Avoid quadratic behavior on large inputs.
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_097944
tests
easy
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, stdlib-only, must be streaming-friendly. Difficulty: easy. Ensure the API is testable via dependency injection.
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_097945
tests
medium
Write a thorough test suite for a Python component used for validation. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must be streaming-friendly, must include docstrings. Difficulty: medium. 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_097946
tests
expert
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 easy to extend, must include docstrings. Difficulty: expert. Include a small CLI example if relevant.
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": true, "seed": 1337 }
pygod_097947
tests
hard
Write a thorough test suite for a Python component used for data modeling. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must handle Windows paths safely, must be streaming-friendly. 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_097948
tests
expert
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 type hints. Difficulty: expert. Avoid quadratic behavior on large inputs.
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_097949
tests
medium
Write a thorough test suite for a Python component used for file synchronization. Requirements: cover edge cases, invalid inputs, and behavior invariants. Constraints: must avoid global state, must be streaming-friendly, must be memory-efficient. Difficulty: medium. 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": false, "seed": 1337 }
pygod_097950
algorithms
hard
Design and implement an algorithm for validation. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must handle Windows paths safely, must include type hints, must avoid global state, must be easy to extend. Difficulty: hard. 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": true, "seed": 1337 }
pygod_097951
algorithms
easy
Design and implement an algorithm for log processing. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be streaming-friendly, must include docstrings, must avoid global state, must provide clear error messages. Difficulty: easy. Include a small CLI example if relevant.
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_097952
algorithms
easy
Design and implement an algorithm for ETL pipelines. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be easy to extend, must include tests, must be memory-efficient. Difficulty: easy. Ensure the API is testable via dependency injection.
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_097953
algorithms
medium
Design and implement an algorithm for CLI tooling. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: stdlib-only, must be easy to extend. Difficulty: medium. Include a small CLI example if relevant.
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_097954
algorithms
hard
Design and implement an algorithm for event dispatching. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must include docstrings, must include tests, must be streaming-friendly, must handle Windows paths safely. Difficulty: hard. Avoid quadratic behavior on large inputs.
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_097955
algorithms
expert
Design and implement an algorithm for ETL pipelines. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must handle Windows paths safely, must be easy to extend. Difficulty: expert. Provide helpful exceptions with actionable messages.
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_097956
algorithms
medium
Design and implement an algorithm for rate limiting. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must avoid global state, must provide clear error messages. 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_097957
algorithms
easy
Design and implement an algorithm for time series. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be streaming-friendly, must handle Windows paths safely, must include type hints, must include tests. Difficulty: easy. Provide helpful exceptions with actionable messages.
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_097958
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 streaming-friendly, must be easy to extend. Difficulty: hard. Support both Windows and POSIX paths correctly.
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_097959
algorithms
expert
Design and implement an algorithm for CLI tooling. Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests. Constraints: must be memory-efficient, must avoid global state, must handle Windows paths safely. Difficulty: expert. Include a small CLI example if relevant.
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_097960
typing
medium
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 provide clear error messages, must avoid global state, stdlib-only, must handle Windows paths safely. Difficulty: medium. 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": false, "seed": 1337 }
pygod_097961
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 be easy to extend, must include tests, must be memory-efficient, must include docstrings. Difficulty: hard. Ensure the API is testable via dependency injection.
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_097962
typing
expert
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 provide clear error messages, must avoid global state, must handle Windows paths safely. Difficulty: expert. Include a small CLI example if relevant.
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_097963
typing
hard
Improve typing and robustness of a Python module used for configuration loading. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must include type hints, must be streaming-friendly. Difficulty: hard. Include a small CLI example if relevant.
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_097964
typing
expert
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 handle Windows paths safely, must be easy to extend. Difficulty: expert. 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_097965
typing
expert
Improve typing and robustness of a Python module used for parsing. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must be easy to extend, must handle Windows paths safely, must be streaming-friendly. Difficulty: expert. 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_097966
typing
hard
Improve typing and robustness of a Python module used for configuration loading. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must be streaming-friendly, stdlib-only, must handle Windows paths safely, must be easy to extend. 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_097967
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 include tests, must handle Windows paths safely, must avoid global state, stdlib-only. Difficulty: medium. 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_097968
typing
medium
Improve typing and robustness of a Python module used for event dispatching. Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests. Constraints: must provide clear error messages, must avoid global state, must be memory-efficient, stdlib-only. Difficulty: medium. Include a small CLI example if relevant.
Deliverable: corrected code and verification 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_097969
typing
expert
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 be streaming-friendly, must provide clear error messages. Difficulty: expert. Provide helpful exceptions with actionable messages.
Deliverable: corrected code and verification 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_097970
performance
medium
Optimize a Python workflow for parsing. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be memory-efficient, stdlib-only, must include type hints, must include tests. Difficulty: medium. Ensure the API is testable via dependency injection.
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_097971
performance
expert
Optimize a Python workflow for configuration loading. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be memory-efficient, must include docstrings. Difficulty: expert. 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_097972
performance
hard
Optimize a Python workflow for configuration loading. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be memory-efficient, must avoid global state, must include docstrings. Difficulty: hard. Avoid quadratic behavior on large inputs.
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": true, "seed": 1337 }
pygod_097973
performance
hard
Optimize a Python workflow for metrics aggregation. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must be easy to extend, must handle Windows paths safely. Difficulty: hard. 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": true, "seed": 1337 }
pygod_097974
performance
easy
Optimize a Python workflow for metrics aggregation. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must include type hints, must handle Windows paths safely, must be streaming-friendly, must include tests. Difficulty: easy. Provide helpful exceptions with actionable messages.
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_097975
performance
easy
Optimize a Python workflow for event dispatching. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must include type hints, stdlib-only, must include docstrings. Difficulty: easy. Provide helpful exceptions with actionable messages.
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": false, "seed": 1337 }
pygod_097976
performance
easy
Optimize a Python workflow for parsing. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must provide clear error messages, must handle Windows paths safely. Difficulty: easy. Avoid quadratic behavior on large inputs.
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": false, "seed": 1337 }
pygod_097977
performance
expert
Optimize a Python workflow for configuration loading. Requirements: provide an optimized implementation and a small benchmark harness. Constraints: must include type hints, stdlib-only, must be streaming-friendly, must be memory-efficient. Difficulty: expert. Ensure the API is testable via dependency injection.
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_097978
concurrency
hard
Implement a concurrent Python solution for report generation. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: stdlib-only, must be streaming-friendly, must provide clear error messages, must be memory-efficient. Difficulty: hard. Support both Windows and POSIX paths correctly.
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_097979
concurrency
expert
Implement a concurrent Python solution for report generation. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must include tests, must include docstrings. Difficulty: expert. Support both Windows and POSIX paths correctly.
Deliverable: corrected code and verification 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_097980
concurrency
easy
Implement a concurrent Python solution for data modeling. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must include docstrings, must include tests, must be memory-efficient, must be easy to extend. Difficulty: easy. Support both Windows and POSIX paths correctly.
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_097981
concurrency
medium
Implement a concurrent Python solution for rate limiting. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must be easy to extend, must avoid global state, must include type hints. Difficulty: medium. Guarantee deterministic output ordering.
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_097982
concurrency
medium
Implement a concurrent Python solution for CLI tooling. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must be memory-efficient, must include type hints, must be streaming-friendly, must be easy to extend. Difficulty: medium. Guarantee deterministic output ordering.
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_097983
concurrency
easy
Implement a concurrent Python solution for data modeling. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: must be streaming-friendly, must include tests, must include docstrings, must be easy to extend. Difficulty: easy. Provide helpful exceptions with actionable messages.
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_097984
concurrency
easy
Implement a concurrent Python solution for data modeling. Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests. Constraints: stdlib-only, must handle Windows paths safely, must include docstrings. Difficulty: easy. Support both Windows and POSIX paths correctly.
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_097985
api_design
medium
Design a small, production-grade Python API for rate limiting. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must be memory-efficient, stdlib-only. Difficulty: medium. Provide helpful exceptions with actionable messages.
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", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097986
api_design
hard
Design a small, production-grade Python API for parsing. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must be easy to extend, must include docstrings, must avoid global state. Difficulty: hard. Ensure the API is testable via dependency injection.
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_097987
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 be streaming-friendly, must include tests, must avoid global state, must include docstrings. Difficulty: medium. Ensure the API is testable via dependency injection.
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_097988
api_design
medium
Design a small, production-grade Python API for configuration loading. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: stdlib-only, must include type hints, must include tests, must be memory-efficient. Difficulty: medium. 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", "interfaces", "dataclasses" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097989
api_design
easy
Design a small, production-grade Python API for ETL pipelines. Requirements: define data models and interfaces, implement reference version, include tests. Constraints: must handle Windows paths safely, must avoid global state, must include tests. Difficulty: easy. 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": false, "seed": 1337 }
pygod_097990
packaging
easy
Create a small, production-ready Python package for CLI tooling. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must include docstrings, must include tests, must handle Windows paths safely, must be memory-efficient. Difficulty: easy. Avoid quadratic behavior on large inputs.
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_097991
packaging
easy
Create a small, production-ready Python package for rate limiting. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must handle Windows paths safely, must provide clear error messages. Difficulty: easy. Include a small CLI example if relevant.
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_097992
packaging
medium
Create a small, production-ready Python package for CLI tooling. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must include type hints, must include tests, must be streaming-friendly, must avoid global state. 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_097993
packaging
easy
Create a small, production-ready Python package for metrics aggregation. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must be memory-efficient, 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_097994
packaging
easy
Create a small, production-ready Python package for report generation. Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml. Constraints: must be streaming-friendly, stdlib-only. Difficulty: easy. Support both Windows and POSIX paths correctly.
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_097995
security_safe
expert
Write secure, defensive Python code for log processing. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must include type hints, stdlib-only, must avoid global state, must include tests. Difficulty: expert. 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", "security", "validation" ], "has_code": true, "requires_thinking": true, "seed": 1337 }
pygod_097996
security_safe
easy
Write secure, defensive Python code for caching layer. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must include docstrings, must handle Windows paths safely, must avoid global state, must be easy to extend. 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", "security", "validation" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097997
security_safe
easy
Write secure, defensive Python code for telemetry ingestion. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must handle Windows paths safely, must include type hints, must include docstrings, must be memory-efficient. 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", "security", "validation" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_097998
security_safe
easy
Write secure, defensive Python code for ETL pipelines. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must include docstrings, must include type hints. Difficulty: easy. Include a small CLI example if relevant.
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_097999
security_safe
medium
Write secure, defensive Python code for telemetry ingestion. Requirements: input validation, safe file handling, prevent path traversal, include tests. Constraints: must handle Windows paths safely, must be easy to extend, must include tests, must include docstrings. 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", "security", "validation" ], "has_code": true, "requires_thinking": false, "seed": 1337 }
pygod_098000
bugfix
hard
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: must be memory-efficient, must handle Windows paths safely, must provide clear error messages, must be easy to extend. 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 }