{"task_id": "js-snowflake-ids", "title": "Snowflake-style IDs silently collide after 1024 ms (32-bit bitwise ops)", "language": "javascript", "category": "numeric-type-semantics", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Event IDs collide after 1024 ms, corrupting the event log\n\n## Summary\n\nOur event-sourced store assigns each event a snowflake-style identifier\nbuilt from a custom epoch (2025-01-01), a node id and a per-millisecond\nsequence counter. After investigation we found that two events exactly 1024\nms apart with the same node and sequence receive THE SAME id, and ids are\nnot monotonic across the 1024 ms boundary either.\n\nOnce an id repeats, the store silently overwrites one event with the other\nduring index rebuild, `since(id)` returns wrong results, and deduplication\nagainst upstream producers breaks. Short manual tests pass because small\ntimestamps (near the custom epoch) fit in 31 bits, and only realistic\nproduction timestamps (milliseconds since 2025) overflow.\n\n## Environment\n\n- Node.js 22+, ESM, no dependencies\n- Code layout: `src/` (ids, store, load, api)\n\n## Reproduction\n\n```js\nimport { makeId, CUSTOM_EPOCH } from \"./src/ids.js\";\n\nconst t = Date.now(); // realistic production timestamp\nconst a = makeId(t, 5, 7);\nconst b = makeId(t + 1024, 5, 7);\nconsole.log(a, b, a === b); // equal -> BUG\n```\n\nExpected: ids are unique for any distinct (timestamp, sequence, node) triple\nwith timestamp differences >= 1 ms, strictly increasing with time per node,\nand survive a JSON persistence round trip bit-for-bit.\n\n## Constraints\n\n- `makeId(tsMs, seq, nodeId)` signature, the custom epoch, and the\n 41/10/12 bit layout stay stable.\n- Ids may be represented as strings internally, but `EventLog` public API\n (`record`, `all`, `since`, `find`) stays stable and must accept and return\n the same id representation that `makeId` produces.\n- Ids must remain sortable by time.", "repo_files": [{"filename": "package.json", "content": "{\n \"name\": \"event-log\",\n \"version\": \"1.0.0\",\n \"type\": \"module\",\n \"private\": true\n}\n"}, {"filename": "src/api.js", "content": "/** Public facade. */\n\nimport { EventStore } from \"./store.js\";\nimport { rebuildIndex } from \"./load.js\";\n\nexport class EventLog {\n constructor(filePath) {\n this.store = new EventStore(filePath);\n }\n\n record(type, payload, tsMs) {\n return this.store.append(type, payload, tsMs);\n }\n\n all() {\n return this.store.readAll();\n }\n\n since(id) {\n const from = Number(id);\n return this.store.readAll().filter((event) => Number(event.id) > from);\n }\n\n find(id) {\n return rebuildIndex(this.store.readAll()).get(String(id));\n }\n}\n"}, {"filename": "src/ids.js", "content": "/** Snowflake-style identifiers.\n *\n * Layout (41 bits millis, 10 bits node, 12 bits sequence) relative to a\n * custom epoch (2025-01-01). */\n\nexport const CUSTOM_EPOCH = Date.UTC(2025, 0, 1);\nexport const NODE_ID = 7;\nexport const NODE_MASK = 0x3ff;\nexport const SEQ_MASK = 0xfff;\nexport const SEQ_PERIOD_MS = 1024;\n\nexport function makeId(tsMs, seq, nodeId = NODE_ID) {\n const delta = tsMs - CUSTOM_EPOCH;\n return (delta << 22) | ((nodeId & NODE_MASK) << 12) | (seq & SEQ_MASK);\n}\n"}, {"filename": "src/load.js", "content": "/** Loading and index rebuilding. */\n\nimport { readFileSync } from \"node:fs\";\n\nexport function rebuildIndex(events) {\n const index = new Map();\n for (const event of events) {\n index.set(String(event.id), event);\n }\n return index;\n}\n\nexport function loadStore(filePath) {\n return rebuildIndex(JSON.parse(readFileSync(filePath, \"utf8\")).events);\n}\n"}, {"filename": "src/store.js", "content": "/** Append-only event store with JSON file persistence. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nimport { NODE_ID, SEQ_MASK, makeId } from \"./ids.js\";\n\nexport class EventStore {\n constructor(filePath) {\n this.filePath = filePath;\n this.events = [];\n this.lastTs = -1;\n this.seq = 0;\n if (existsSync(filePath)) {\n const raw = JSON.parse(readFileSync(filePath, \"utf8\"));\n this.events = raw.events;\n for (const event of this.events) {\n this.lastTs = Math.max(this.lastTs, event.ts);\n }\n }\n }\n\n append(type, payload, tsMs = Date.now()) {\n if (tsMs === this.lastTs) {\n this.seq = (this.seq + 1) % (SEQ_MASK + 1);\n } else {\n this.lastTs = tsMs;\n this.seq = 0;\n }\n const id = makeId(tsMs, this.seq, NODE_ID);\n const event = { id, type, payload, ts: tsMs };\n this.events.push(event);\n this.flush();\n return id;\n }\n\n flush() {\n mkdirSync(dirname(this.filePath), { recursive: true });\n writeFileSync(this.filePath, JSON.stringify({ events: this.events }));\n }\n\n readAll() {\n return this.events.slice();\n }\n}\n"}], "test_files": [{"filename": "run_tests.mjs", "content": "/** Hidden verification suite (TAP output). */\n\nimport { mkdtempSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { CUSTOM_EPOCH, NODE_ID, makeId } from \"../src/ids.js\";\nimport { EventLog } from \"../src/api.js\";\nimport { rebuildIndex, loadStore } from \"../src/load.js\";\nimport { check, equal, deepEqual, report, assert } from \"./tap.mjs\";\n\nconst tmp = mkdtempSync(join(tmpdir(), \"eventlog-\"));\n\nfunction t_no_collision_across_seq_period() {\n const t = CUSTOM_EPOCH + 5_000_000;\n const a = makeId(t, 5, 7);\n const b = makeId(t + 1024, 5, 7);\n assert(String(a) !== String(b), `ids 1024ms apart must differ: a=${a} b=${b}`);\n}\n\nfunction t_monotonic_across_1024ms_boundary() {\n // the high 10 bits of the millisecond delta wrap every 1024 ms; ids must\n // keep increasing across the wrap\n let previous = null;\n for (let delta = 0; delta <= 1100; delta += 1) {\n const id = BigInt(makeId(CUSTOM_EPOCH + delta, 0, 7));\n if (previous !== null) {\n assert(id > previous, `ids must increase with time: delta=${delta}, ${id} <= ${previous}`);\n }\n previous = id;\n }\n}\n\nfunction t_realistic_epoch_unique() {\n const t = 1_792_000_000_000; // a realistic \"now\" in ms\n const ids = new Set();\n for (let k = 0; k < 8; k += 1) {\n ids.add(String(makeId(t + k * 1024, 3, NODE_ID)));\n }\n equal(ids.size, 8, `expected 8 distinct ids across 1024ms steps, got ${ids.size}`);\n const burst = new Set();\n for (let k = 0; k < 8; k += 1) {\n for (let seq = 0; seq < 3; seq += 1) {\n burst.add(String(makeId(t + k * 1024, seq, NODE_ID)));\n }\n }\n equal(burst.size, 24, `expected 24 distinct ids in the burst, got ${burst.size}`);\n}\n\nfunction t_masks_and_format() {\n const t = CUSTOM_EPOCH + 10;\n const id = makeId(t, 5000, 2000);\n // 5000 & 0xfff = 904; 2000 & 0x3ff = 976\n const expected = (BigInt(t - CUSTOM_EPOCH) << 22n) | (976n << 12n) | 904n;\n equal(BigInt(id), expected, `masked layout mismatch: ${id}`);\n assert(BigInt(id) > 0n, \"id must be positive\");\n}\n\nfunction t_append_and_read_all() {\n const path = join(tmp, \"store-a.json\");\n const log = new EventLog(path);\n const t = 1_792_000_000_000;\n const id1 = log.record(\"created\", { n: 1 }, t);\n const id2 = log.record(\"updated\", { n: 2 }, t + 5);\n const id3 = log.record(\"updated\", { n: 3 }, t + 5);\n const all = log.all();\n equal(all.length, 3, `expected 3 events, got ${all.length}`);\n equal(String(all[0].id), String(id1), \"first id mismatch\");\n equal(String(all[1].id), String(id2), \"second id mismatch\");\n equal(String(all[2].id), String(id3), \"third id mismatch\");\n assert(BigInt(id2) < BigInt(id3), \"same-ms events must increase by sequence\");\n equal(all[1].type, \"updated\", \"type mismatch\");\n}\n\nfunction t_since_id() {\n const path = join(tmp, \"store-b.json\");\n const log = new EventLog(path);\n const t = 1_792_000_100_000;\n const first = log.record(\"a\", {}, t);\n log.record(\"b\", {}, t + 10);\n log.record(\"c\", {}, t + 20);\n const later = log.since(first);\n equal(later.length, 2, `expected 2 events after the first, got ${later.length}`);\n}\n\nfunction t_rebuild_index_counts() {\n const path = join(tmp, \"store-c.json\");\n const log = new EventLog(path);\n const t = 1_792_000_200_000;\n for (let i = 0; i < 5; i += 1) {\n log.record(\"x\", { i }, t + i);\n }\n const index = rebuildIndex(log.all());\n equal(index.size, 5, `index must hold 5 events, got ${index.size}`);\n const loaded = loadStore(path);\n equal(loaded.size, 5, `loaded index must hold 5 events, got ${loaded.size}`);\n for (const key of loaded.keys()) {\n assert(BigInt(key) > 0n, `loaded id must be positive: ${key}`);\n }\n}\n\nfunction t_record_and_find() {\n const path = join(tmp, \"store-d.json\");\n const log = new EventLog(path);\n const t = 1_792_000_300_000;\n const id = log.record(\"thing\", { hello: \"world\" }, t);\n const found = log.find(id);\n assert(found !== undefined, \"find(id) must return the event\");\n deepEqual(found.payload, { hello: \"world\" }, \"payload mismatch\");\n // JSON round trip must preserve the id exactly\n const raw = JSON.parse(JSON.stringify({ id }));\n equal(String(raw.id), String(id), \"id must survive JSON round trip exactly\");\n}\n\ncheck(\"ids::no_collision_across_seq_period\", t_no_collision_across_seq_period);\ncheck(\"ids::monotonic_across_1024ms_boundary\", t_monotonic_across_1024ms_boundary);\ncheck(\"ids::realistic_epoch_unique\", t_realistic_epoch_unique);\ncheck(\"ids::masks_and_format\", t_masks_and_format);\ncheck(\"store::append_and_read_all\", t_append_and_read_all);\ncheck(\"api::since_id\", t_since_id);\ncheck(\"load::rebuild_index_counts\", t_rebuild_index_counts);\ncheck(\"api::record_and_find\", t_record_and_find);\n\nprocess.exit(report());\n"}, {"filename": "tap.mjs", "content": "/** Minimal TAP-style test helper. */\n\nconst results = [];\n\nexport function check(name, fn) {\n try {\n fn();\n results.push({ ok: true, name });\n } catch (err) {\n results.push({ ok: false, name, diag: `${err.message}` });\n }\n}\n\nexport function assert(cond, message) {\n if (!cond) {\n throw new Error(message || \"assertion failed\");\n }\n}\n\nexport function equal(actual, expected, message) {\n if (actual !== expected) {\n throw new Error(`${message || \"not equal\"}: got ${String(actual)}, want ${String(expected)}`);\n }\n}\n\nexport function deepEqual(actual, expected, message) {\n const a = JSON.stringify(actual);\n const b = JSON.stringify(expected);\n if (a !== b) {\n throw new Error(`${message || \"not deep equal\"}: got ${a}, want ${b}`);\n }\n}\n\nexport function report() {\n let failed = 0;\n results.forEach((r, i) => {\n if (r.ok) {\n console.log(`ok ${i + 1} - ${r.name}`);\n } else {\n failed += 1;\n console.log(`not ok ${i + 1} - ${r.name}`);\n console.log(` # ${r.diag}`);\n }\n });\n return failed === 0 ? 0 : 1;\n}\n"}], "gold_patch": "--- a/src/api.js\n+++ b/src/api.js\n@@ -17,8 +17,8 @@\n }\n \n since(id) {\n- const from = Number(id);\n- return this.store.readAll().filter((event) => Number(event.id) > from);\n+ const from = BigInt(String(id));\n+ return this.store.readAll().filter((event) => BigInt(String(event.id)) > from);\n }\n \n find(id) {\n--- a/src/ids.js\n+++ b/src/ids.js\n@@ -1,7 +1,14 @@\n /** Snowflake-style identifiers.\n *\n * Layout (41 bits millis, 10 bits node, 12 bits sequence) relative to a\n- * custom epoch (2025-01-01). */\n+ * custom epoch (2025-01-01).\n+ *\n+ * JavaScript bitwise operators operate on 32-bit signed integers, so the\n+ * previous Number-based implementation silently wrapped (and collided) for\n+ * timestamps more than 2^10 ms past the epoch. All arithmetic below is done\n+ * with BigInt and the id is returned as a decimal string, which is exact in\n+ * JSON (a raw Number would lose precision above 2^53).\n+ */\n \n export const CUSTOM_EPOCH = Date.UTC(2025, 0, 1);\n export const NODE_ID = 7;\n@@ -10,6 +17,8 @@\n export const SEQ_PERIOD_MS = 1024;\n \n export function makeId(tsMs, seq, nodeId = NODE_ID) {\n- const delta = tsMs - CUSTOM_EPOCH;\n- return (delta << 22) | ((nodeId & NODE_MASK) << 12) | (seq & SEQ_MASK);\n+ const delta = BigInt(tsMs - CUSTOM_EPOCH);\n+ const node = BigInt(nodeId) & BigInt(NODE_MASK);\n+ const sequence = BigInt(seq) & BigInt(SEQ_MASK);\n+ return ((delta << 22n) | (node << 12n) | sequence).toString();\n }\n", "test_command": ["node", "tests/run_tests.mjs"], "fail_to_pass": ["ids::no_collision_across_seq_period", "ids::monotonic_across_1024ms_boundary", "ids::realistic_epoch_unique"], "pass_to_pass": ["ids::masks_and_format", "store::append_and_read_all", "api::since_id", "load::rebuild_index_counts", "api::record_and_find"], "time_limit_s": 60, "sandbox_image": "node:22-slim", "sandbox_system_deps": []} {"task_id": "py-async-reservation", "title": "Concurrent checkout oversells the same seat under interleaved awaits", "language": "python", "category": "concurrency-async", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Concurrent checkout can sell the same seat twice\n\n## Summary\n\nOur theater reservation service oversells seats when many customers check out\nat the same moment. A load test with 200 concurrent bookings for the same event\nshowed 3 successful reservations for seat B12, and the final holder recorded by\nthe database was a customer who was not the first to pay. No exceptions were\nraised: every client received what looked like a confirmed reservation.\n\nThe service layer and the async persistence layer both look correct in\nisolation, and all sequential (single-user) integration tests pass. The defect\nonly appears when reservations for the same seat interleave.\n\n## Environment\n\n- Python 3.11+, single event loop (`asyncio.run` for tests, uvicorn in prod)\n- Code layout: `service/` package (models, async db, booking, api, report)\n\n## Reproduction\n\n```python\nimport asyncio\nfrom service.api import TheaterAPI\n\nasync def main():\n api = TheaterAPI()\n results = await asyncio.gather(*[\n api.book(\"evt-900\", \"B12\", f\"user-{i}\") for i in range(12)\n ])\n ok = [r for r in results if hasattr(r, \"reserved_at\")]\n print(\"successful reservations:\", len(ok))\n print(\"holder in db:\", api.db.holder(\"evt-900\", \"B12\"))\n print(\"holder is winner:\", api.db.holder(\"evt-900\", \"B12\") == (ok[0].user if ok else None))\n\nasyncio.run(main())\n```\n\nExpected: exactly 1 successful reservation; the remaining 11 requests fail\nwith `SeatTakenError`; the db holder is the winner; audit entries must be\nconsistent with outcomes (one reserve-commit per held seat).\n\nActual (buggy): all 12 requests succeed; the db keeps only the last writer;\naudit shows 12 commits for 1 held seat.\n\n## Constraints\n\n- Public API of `TheaterAPI` and `BookingService` must not change.\n- `AsyncReservationDB` I/O latency per operation must be preserved (same number\n of awaits per successful booking).\n- Audit semantics: every reservation attempt and its outcome must be recorded.\n- `service/report.py` and `service/models.py` are not part of the defect.", "repo_files": [{"filename": "service/__init__.py", "content": "\"\"\"Theater reservation service.\"\"\"\n"}, {"filename": "service/api.py", "content": "\"\"\"Public facade used by the checkout frontend.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .booking import BookingService\nfrom .db import AsyncReservationDB\nfrom .models import Reservation, SeatTakenError\n\n\nclass TheaterAPI:\n def __init__(self) -> None:\n self._db = AsyncReservationDB()\n self._booking = BookingService(self._db)\n\n @property\n def db(self) -> AsyncReservationDB:\n return self._db\n\n async def book(self, event_id: str, seat_id: str, user: str) -> Reservation | SeatTakenError:\n try:\n return await self._booking.reserve(event_id, seat_id, user)\n except SeatTakenError as exc:\n return exc\n\n async def cancel(self, event_id: str, seat_id: str) -> None:\n await self._booking.release(event_id, seat_id)\n"}, {"filename": "service/booking.py", "content": "\"\"\"Booking service: turns a seat request into a durable reservation.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .db import AsyncReservationDB\nfrom .models import Reservation, SeatTakenError\n\n\nclass BookingService:\n def __init__(self, db: AsyncReservationDB) -> None:\n self._db = db\n\n async def reserve(self, event_id: str, seat_id: str, user: str) -> Reservation:\n holder = await self._db.get_holder(event_id, seat_id)\n if holder is not None:\n await self._db.audit(\n \"reserve-rejected\",\n event=event_id,\n seat=seat_id,\n user=user,\n holder=holder,\n )\n raise SeatTakenError(event_id, seat_id, holder)\n\n # Record the attempt before committing. This await yields control and\n # lets other bookings for the same seat run their check.\n await self._db.audit(\n \"reserve-attempt\", event=event_id, seat=seat_id, user=user\n )\n\n await self._db.set_holder(event_id, seat_id, user)\n await self._db.audit(\n \"reserve-commit\", event=event_id, seat=seat_id, user=user\n )\n return Reservation(event_id=event_id, seat_id=seat_id, user=user)\n\n async def release(self, event_id: str, seat_id: str) -> None:\n await self._db.audit(\"release\", event=event_id, seat=seat_id)\n await self._db.clear_holder(event_id, seat_id)\n"}, {"filename": "service/db.py", "content": "\"\"\"Async persistence layer.\n\nEvery operation performs a real network round trip before touching state, so\nany code that runs *between* two awaits of this layer can be interleaved with\nother callers on the same event loop.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\n\nIO_LATENCY = 0.002\n\n\nclass AsyncReservationDB:\n def __init__(self) -> None:\n self._holders: dict[tuple[str, str], str] = {}\n self._audit: list[dict] = []\n\n async def get_holder(self, event_id: str, seat_id: str) -> str | None:\n await asyncio.sleep(IO_LATENCY)\n return self._holders.get((event_id, seat_id))\n\n async def set_holder(self, event_id: str, seat_id: str, user: str) -> None:\n await asyncio.sleep(IO_LATENCY)\n self._holders[(event_id, seat_id)] = user\n\n async def clear_holder(self, event_id: str, seat_id: str) -> None:\n await asyncio.sleep(IO_LATENCY)\n self._holders.pop((event_id, seat_id), None)\n\n async def audit(self, kind: str, **fields) -> None:\n await asyncio.sleep(IO_LATENCY)\n self._audit.append({\"kind\": kind, **fields})\n\n # --- synchronous read helpers (reports, tests) ---\n\n def holder(self, event_id: str, seat_id: str) -> str | None:\n return self._holders.get((event_id, seat_id))\n\n def audit_entries(self, kind: str | None = None) -> list[dict]:\n if kind is None:\n return list(self._audit)\n return [e for e in self._audit if e[\"kind\"] == kind]\n\n def held_seats(self, event_id: str) -> int:\n return sum(1 for (ev, _seat) in self._holders if ev == event_id)\n"}, {"filename": "service/models.py", "content": "\"\"\"Domain models for the theater reservation service.\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timezone\n\n\ndef utcnow() -> datetime:\n return datetime.now(timezone.utc)\n\n\n@dataclass(frozen=True)\nclass Event:\n event_id: str\n name: str\n seat_count: int\n\n\n@dataclass(frozen=True)\nclass Reservation:\n event_id: str\n seat_id: str\n user: str\n reserved_at: datetime = field(default_factory=utcnow)\n\n @property\n def key(self) -> tuple[str, str]:\n return (self.event_id, self.seat_id)\n\n\nclass SeatTakenError(Exception):\n \"\"\"Raised when the requested seat is already held by another user.\"\"\"\n\n def __init__(self, event_id: str, seat_id: str, holder: str):\n self.event_id = event_id\n self.seat_id = seat_id\n self.holder = holder\n super().__init__(f\"seat {seat_id} of event {event_id} is held by {holder}\")\n"}, {"filename": "service/report.py", "content": "\"\"\"Occupancy reporting.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .db import AsyncReservationDB\n\n\ndef occupancy_report(db: AsyncReservationDB, event_id: str) -> dict:\n return {\n \"event_id\": event_id,\n \"held_seats\": db.held_seats(event_id),\n \"attempts\": len(db.audit_entries(\"reserve-attempt\")),\n \"commits\": len(db.audit_entries(\"reserve-commit\")),\n \"rejections\": len(db.audit_entries(\"reserve-rejected\")),\n \"consistent\": len(db.audit_entries(\"reserve-commit\")) == db.held_seats(event_id),\n }\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport asyncio\nimport os\nimport sys\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom service.api import TheaterAPI\nfrom service.models import Reservation, SeatTakenError\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001 - report any failure as TAP failure\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\ndef run_async(coro_fn):\n return asyncio.run(coro_fn())\n\n\n# --- fail_to_pass ---\n\ndef t_no_oversell():\n async def scenario():\n api = TheaterAPI()\n results = await asyncio.gather(*[\n api.book(\"evt-1\", \"A1\", f\"user-{i}\") for i in range(12)\n ])\n ok = [r for r in results if isinstance(r, Reservation)]\n rejected = [r for r in results if isinstance(r, SeatTakenError)]\n assert len(ok) == 1, f\"exactly one reservation must succeed, got {len(ok)}\"\n assert len(rejected) == 11, f\"11 must be rejected, got {len(rejected)}\"\n winner = ok[0]\n assert api.db.holder(\"evt-1\", \"A1\") == winner.user, (\n f\"db holder {api.db.holder('evt-1', 'A1')!r} is not the winner {winner.user!r}\"\n )\n assert len({r.user for r in ok}) == 1, \"duplicate winners\"\n return api\n\n run_async(scenario)\n\n\ndef t_audit_matches_outcomes():\n async def scenario():\n api = TheaterAPI()\n await asyncio.gather(*[\n api.book(\"evt-2\", \"C7\", f\"user-{i}\") for i in range(12)\n ])\n report = api.report_occupancy(\"evt-2\") if hasattr(api, \"report_occupancy\") else None\n from service.report import occupancy_report\n report = occupancy_report(api.db, \"evt-2\")\n assert report[\"consistent\"] is True, (\n f\"commits ({report['commits']}) must equal held seats ({report['held_seats']})\"\n )\n assert report[\"commits\"] == 1, f\"exactly one commit expected, got {report['commits']}\"\n assert report[\"attempts\"] == 12, f\"12 attempts expected, got {report['attempts']}\"\n assert report[\"rejections\"] == 11, f\"11 rejections expected, got {report['rejections']}\"\n\n run_async(scenario)\n\n\n# --- pass_to_pass ---\n\ndef t_sequential_reserve():\n async def scenario():\n api = TheaterAPI()\n r = await api.book(\"evt-3\", \"D1\", \"alice\")\n assert isinstance(r, Reservation), f\"expected Reservation, got {r!r}\"\n assert r.user == \"alice\"\n assert api.db.holder(\"evt-3\", \"D1\") == \"alice\"\n\n run_async(scenario)\n\n\ndef t_double_book_fails():\n async def scenario():\n api = TheaterAPI()\n r1 = await api.book(\"evt-4\", \"E2\", \"bob\")\n assert isinstance(r1, Reservation)\n r2 = await api.book(\"evt-4\", \"E2\", \"carol\")\n assert isinstance(r2, SeatTakenError), f\"expected SeatTakenError, got {r2!r}\"\n assert r2.holder == \"bob\"\n assert api.db.holder(\"evt-4\", \"E2\") == \"bob\"\n\n run_async(scenario)\n\n\ndef t_release_then_rebook():\n async def scenario():\n api = TheaterAPI()\n await api.book(\"evt-5\", \"F9\", \"dan\")\n await api.cancel(\"evt-5\", \"F9\")\n assert api.db.holder(\"evt-5\", \"F9\") is None\n r = await api.book(\"evt-5\", \"F9\", \"erin\")\n assert isinstance(r, Reservation), f\"rebook must succeed, got {r!r}\"\n assert api.db.holder(\"evt-5\", \"F9\") == \"erin\"\n\n run_async(scenario)\n\n\ndef t_reservation_fields():\n r = Reservation(\"evt-6\", \"G3\", \"frank\")\n assert r.event_id == \"evt-6\"\n assert r.seat_id == \"G3\"\n assert r.user == \"frank\"\n assert r.key == (\"evt-6\", \"G3\")\n assert r.reserved_at is not None\n\n\ndef t_occupancy_counts():\n from service.report import occupancy_report\n\n async def scenario():\n api = TheaterAPI()\n await api.book(\"evt-7\", \"H1\", \"u1\")\n await api.book(\"evt-7\", \"H2\", \"u2\")\n return api\n\n api = run_async(scenario)\n report = occupancy_report(api.db, \"evt-7\")\n assert report[\"held_seats\"] == 2, report\n assert report[\"commits\"] == 2, report\n assert report[\"consistent\"] is True, report\n\n\ndef main():\n check(\"booking::no_oversell_under_concurrency\", t_no_oversell)\n check(\"booking::audit_matches_outcomes\", t_audit_matches_outcomes)\n check(\"booking::sequential_reserve\", t_sequential_reserve)\n check(\"booking::double_book_fails\", t_double_book_fails)\n check(\"booking::release_then_rebook\", t_release_then_rebook)\n check(\"models::reservation_fields\", t_reservation_fields)\n check(\"report::occupancy_counts\", t_occupancy_counts)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/service/booking.py\n+++ b/service/booking.py\n@@ -11,24 +11,20 @@\n self._db = db\n \n async def reserve(self, event_id: str, seat_id: str, user: str) -> Reservation:\n- holder = await self._db.get_holder(event_id, seat_id)\n- if holder is not None:\n+ await self._db.audit(\n+ \"reserve-attempt\", event=event_id, seat=seat_id, user=user\n+ )\n+ previous = await self._db.try_claim(event_id, seat_id, user)\n+ if previous is not None:\n await self._db.audit(\n \"reserve-rejected\",\n event=event_id,\n seat=seat_id,\n user=user,\n- holder=holder,\n+ holder=previous,\n )\n- raise SeatTakenError(event_id, seat_id, holder)\n+ raise SeatTakenError(event_id, seat_id, previous)\n \n- # Record the attempt before committing. This await yields control and\n- # lets other bookings for the same seat run their check.\n- await self._db.audit(\n- \"reserve-attempt\", event=event_id, seat=seat_id, user=user\n- )\n-\n- await self._db.set_holder(event_id, seat_id, user)\n await self._db.audit(\n \"reserve-commit\", event=event_id, seat=seat_id, user=user\n )\n--- a/service/db.py\n+++ b/service/db.py\n@@ -2,7 +2,8 @@\n \n Every operation performs a real network round trip before touching state, so\n any code that runs *between* two awaits of this layer can be interleaved with\n-other callers on the same event loop.\n+other callers on the same event loop. State-changing operations must therefore\n+perform their check and their write without an intervening await.\n \"\"\"\n \n from __future__ import annotations\n@@ -25,6 +26,19 @@\n await asyncio.sleep(IO_LATENCY)\n self._holders[(event_id, seat_id)] = user\n \n+ async def try_claim(self, event_id: str, seat_id: str, user: str) -> str | None:\n+ \"\"\"Atomically claim a seat.\n+\n+ Returns the previous holder, or None if the caller won the seat. The\n+ check and the set happen with no await in between, so on a single\n+ event loop no other reservation coroutine can interleave here.\n+ \"\"\"\n+ await asyncio.sleep(IO_LATENCY) # network round trip, before the critical section\n+ previous = self._holders.get((event_id, seat_id))\n+ if previous is None:\n+ self._holders[(event_id, seat_id)] = user\n+ return previous\n+\n async def clear_holder(self, event_id: str, seat_id: str) -> None:\n await asyncio.sleep(IO_LATENCY)\n self._holders.pop((event_id, seat_id), None)\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["booking::no_oversell_under_concurrency", "booking::audit_matches_outcomes"], "pass_to_pass": ["booking::sequential_reserve", "booking::double_book_fails", "booking::release_then_rebook", "models::reservation_fields", "report::occupancy_counts"], "time_limit_s": 120, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "py-decimal-ledger", "title": "Bonus pool allocation loses cents to float rounding", "language": "python", "category": "numeric-precision", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Payroll reconciliation is off by cents after bonus-pool allocation\n\n## Summary\n\nThe nightly payroll reconciliation flags an imbalance for most bonus pools.\nThe ledger allocates a bonus pool across departments in proportion to\nheadcount, but the sum of the allocated adjustments does not equal the pool.\nFinance reports differences of 0.01 USD on many runs and, for small pools,\ndifferences of several cents in the wrong direction.\n\nTwo behaviors are wrong:\n\n1. Allocated parts must sum EXACTLY to the pool (in cents), with at most one\n cent of difference between any two parts.\n2. Half-cent values must round half-up (the accounting convention), not\n round-half-even. `Money(\"0.125\")` must be 0.13 and `Money(\"2.675\")` must be\n 2.68.\n\n## Environment\n\n- Python 3.11+, no third-party dependencies\n- Code layout: `ledger/` package (money, models, payroll, report, loader)\n\n## Reproduction\n\n```python\nfrom ledger.money import Money\nfrom ledger.payroll import run_payroll\nfrom ledger.models import Department\n\npool = Money(\"100.00\")\ndepts = [Department(\"eng\", 3), Department(\"sales\", 3), Department(\"ops\", 3)]\nresult = run_payroll(pool, depts)\nprint(result.total_paid, pool, result.reconciled) # 99.99 100.00 False\n\nparts = Money(\"0.05\").split_evenly(3)\nprint([str(p) for p in parts]) # ['$0.02', '$0.02', '$0.02'] sums to 0.06\n\nprint(Money(\"0.125\").amount, Money(\"2.675\").amount) # 0.12 2.67 (must be 0.13 2.68)\n```\n\n## Constraints\n\n- `Money` public API (`amount`, `parse_money`, `of_cents`, `str`, arithmetic,\n comparisons, `split_evenly`, `allocate`) must stay stable.\n- `Money(\"0.125\").amount == Decimal(\"0.13\")` style equality must hold for the\n corrected type (the attribute may change type; equality with Decimal must\n work).\n- Allocation order must be deterministic: with ties, the earlier weight wins\n the extra cent.\n- `ledger/models.py`, `ledger/report.py` and the JSON loader format are not\n part of the defect.", "repo_files": [{"filename": "ledger/__init__.py", "content": "\"\"\"Payroll ledger: bonus pool allocation and reconciliation.\"\"\"\n"}, {"filename": "ledger/loader.py", "content": "\"\"\"JSON payroll spec loader.\n\nSpec format:\n{\n \"pool\": \"10000.00\",\n \"departments\": [{\"name\": \"eng\", \"headcount\": 3}, ...]\n}\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\n\nfrom .money import Money\nfrom .models import Department\nfrom .payroll import run_payroll\n\n\ndef load_spec(text: str):\n data = json.loads(text)\n pool = Money(data[\"pool\"])\n departments = [\n Department(name=d[\"name\"], headcount=int(d[\"headcount\"]))\n for d in data[\"departments\"]\n ]\n return run_payroll(pool, departments)\n"}, {"filename": "ledger/models.py", "content": "\"\"\"Payroll domain records.\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\nfrom .money import Money\n\n\n@dataclass(frozen=True)\nclass Department:\n name: str\n headcount: int\n\n\n@dataclass(frozen=True)\nclass Adjustment:\n department: str\n amount: Money\n\n\n@dataclass(frozen=True)\nclass PayrollResult:\n pool: Money\n adjustments: tuple\n total_paid: Money\n reconciled: bool\n"}, {"filename": "ledger/money.py", "content": "\"\"\"Monetary amounts and proportional allocation.\n\nAmounts are stored as floats. Display and storage rounding use the built-in\nround(), which is round-half-to-even (\"banker's rounding\").\n\"\"\"\n\nfrom __future__ import annotations\n\nCENT = 0.01\n\n\nclass MoneyError(ValueError):\n \"\"\"Invalid money input (unparsable text, bad allocation weights).\"\"\"\n\n\ndef parse_money(text: str) -> float:\n \"\"\"Parse a display string like \"$1,234.56\" into a float amount.\"\"\"\n if not isinstance(text, str):\n raise MoneyError(f\"cannot parse money from {type(text).__name__}\")\n cleaned = text.strip().lstrip(\"$\").replace(\",\", \"\").replace(\" \", \"\")\n if not cleaned:\n raise MoneyError(\"empty money string\")\n try:\n return float(cleaned)\n except ValueError as exc:\n raise MoneyError(f\"invalid money string: {text!r}\") from exc\n\n\nclass Money:\n __slots__ = (\"amount\",)\n\n def __init__(self, amount) -> None:\n if isinstance(amount, Money):\n self.amount = amount.amount\n elif isinstance(amount, str):\n self.amount = round(parse_money(amount), 2)\n else:\n self.amount = round(float(amount), 2)\n\n @classmethod\n def of_cents(cls, cents: int) -> \"Money\":\n return cls(round(cents / 100.0, 2))\n\n def cents(self) -> int:\n return int(round(self.amount * 100))\n\n def __add__(self, other: \"Money\") -> \"Money\":\n if not isinstance(other, Money):\n return NotImplemented\n return Money(round(self.amount + other.amount, 2))\n\n def __sub__(self, other: \"Money\") -> \"Money\":\n if not isinstance(other, Money):\n return NotImplemented\n return Money(round(self.amount - other.amount, 2))\n\n def __mul__(self, factor: float) -> \"Money\":\n return Money(round(self.amount * float(factor), 2))\n\n def __eq__(self, other) -> bool:\n if isinstance(other, Money):\n return self.amount == other.amount\n return NotImplemented\n\n def __lt__(self, other: \"Money\") -> bool:\n if not isinstance(other, Money):\n return NotImplemented\n return self.amount < other.amount\n\n def __hash__(self) -> int:\n return hash(self.amount)\n\n def __repr__(self) -> str:\n return f\"Money({self.amount!r})\"\n\n def __str__(self) -> str:\n return f\"${self.amount:,.2f}\"\n\n def split_evenly(self, n: int) -> list[\"Money\"]:\n \"\"\"Split into n parts. Each part is the same rounded share.\"\"\"\n if n < 1:\n raise MoneyError(\"cannot split into fewer than 1 part\")\n share = round(self.amount / n, 2)\n return [Money(share) for _ in range(n)]\n\n def allocate(self, weights: list[int]) -> list[\"Money\"]:\n \"\"\"Allocate proportionally to integer weights.\"\"\"\n if not weights:\n return []\n total = sum(weights)\n if total <= 0:\n raise MoneyError(\"weights must be positive in total\")\n return [Money(round(self.amount * w / total, 2)) for w in weights]\n"}, {"filename": "ledger/payroll.py", "content": "\"\"\"Payroll run: allocate a bonus pool across departments.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .models import Adjustment, Department, PayrollResult\nfrom .money import Money\n\n\ndef run_payroll(pool: Money, departments: list[Department]) -> PayrollResult:\n weights = [d.headcount for d in departments]\n shares = pool.allocate(weights)\n adjustments = tuple(\n Adjustment(department=d.name, amount=share)\n for d, share in zip(departments, shares)\n )\n total_paid = Money(0)\n for adj in adjustments:\n total_paid = total_paid + adj.amount\n return PayrollResult(\n pool=pool,\n adjustments=adjustments,\n total_paid=total_paid,\n reconciled=total_paid == pool,\n )\n"}, {"filename": "ledger/report.py", "content": "\"\"\"Reconciliation reporting.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .money import Money\nfrom .models import Adjustment\n\n\ndef reconcile(adjustments, pool: Money) -> dict:\n paid = Money(0)\n for adj in adjustments:\n paid = paid + adj.amount\n return {\n \"pool_cents\": pool.cents(),\n \"paid_cents\": paid.cents(),\n \"difference_cents\": paid.cents() - pool.cents(),\n \"balanced\": paid == pool,\n }\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport json\nimport os\nimport sys\nfrom decimal import Decimal\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom ledger.money import Money, MoneyError, parse_money\nfrom ledger.payroll import run_payroll\nfrom ledger.models import Department\nfrom ledger.report import reconcile\nfrom ledger.loader import load_spec\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\nPOOLS = [\"0.03\", \"0.05\", \"0.07\", \"10.00\", \"99.99\", \"100.00\", \"12345.67\", \"0.01\"]\nCOUNTS = [1, 2, 3, 4, 7, 9]\n\n\ndef t_split_conserves_total():\n for pool in POOLS:\n m = Money(pool)\n for n in COUNTS:\n parts = m.split_evenly(n)\n assert len(parts) == n, f\"{pool} into {n}: wrong part count\"\n total = sum(p.cents() for p in parts)\n assert total == m.cents(), f\"{pool} into {n}: sum {total} != {m.cents()}\"\n amounts = sorted(p.cents() for p in parts)\n assert amounts[-1] - amounts[0] <= 1, (\n f\"{pool} into {n}: parts differ by more than a cent: {amounts}\"\n )\n\n\ndef t_allocate_conserves_total():\n cases = [\n (\"100.00\", [1, 1, 1]),\n (\"100.00\", [3, 3, 3]),\n (\"100.00\", [1, 2, 3]),\n (\"12345.67\", [5, 7, 11]),\n (\"0.03\", [1, 1, 1]),\n (\"1000.00\", [1, 1, 1, 1, 1, 1, 1]),\n (\"75.50\", [2, 5, 0, 1]),\n ]\n for pool, weights in cases:\n m = Money(pool)\n parts = m.allocate(weights)\n assert len(parts) == len(weights), (pool, weights)\n total = sum(p.cents() for p in parts)\n assert total == m.cents(), f\"{pool} x {weights}: sum {total} != {m.cents()}\"\n # zero weight must receive exactly zero\n for w, p in zip(weights, parts):\n if w == 0:\n assert p.cents() == 0, f\"zero weight got {p.cents()} cents\"\n\n\ndef t_half_cent_rounds_half_up():\n assert Money(\"0.125\").cents() == 13, Money(\"0.125\").cents()\n assert Money(\"2.675\").cents() == 268, Money(\"2.675\").cents()\n assert Money(Decimal(\"0.125\")).cents() == 13\n assert Money(\"0.005\").cents() == 1\n assert Money(\"0.015\").cents() == 2\n\n\ndef t_run_payroll_reconciles():\n scenarios = [\n (\"100.00\", [(\"eng\", 3), (\"sales\", 3), (\"ops\", 3)]),\n (\"10000.00\", [(\"a\", 1), (\"b\", 2), (\"c\", 4), (\"d\", 13)]),\n (\"0.05\", [(\"x\", 1), (\"y\", 1), (\"z\", 1)]),\n (\"1.00\", [(\"solo\", 7)]),\n ]\n for pool, depts in scenarios:\n result = run_payroll(Money(pool), [Department(n, h) for n, h in depts])\n assert result.reconciled is True, f\"{pool}: pool not reconciled\"\n assert result.total_paid.cents() == Money(pool).cents(), f\"{pool}: {result.total_paid}\"\n paid = sum(a.amount.cents() for a in result.adjustments)\n assert paid == Money(pool).cents(), f\"{pool}: adjustments sum {paid} cents\"\n\n\ndef t_parse_and_format():\n m = parse_money(\"$1,234.56\")\n assert Money(m).cents() == 123456, m\n assert str(Money(\"$1,234.56\")) == \"$1,234.56\"\n assert str(Money(1000000)) == \"$1,000,000.00\"\n assert str(Money(\"0.01\")) == \"$0.01\"\n assert str(Money(0)) == \"$0.00\"\n try:\n parse_money(\"abc\")\n except MoneyError:\n pass\n else:\n raise AssertionError(\"parse_money('abc') must raise MoneyError\")\n try:\n parse_money(\"\")\n except MoneyError:\n pass\n else:\n raise AssertionError(\"parse_money('') must raise MoneyError\")\n\n\ndef t_of_cents_and_arithmetic():\n assert Money.of_cents(12345) == Money(\"123.45\")\n assert Money.of_cents(1) == Money(\"0.01\")\n assert Money.of_cents(-5) == Money(\"-0.05\")\n assert Money(\"1.10\") + Money(\"2.20\") == Money(\"3.30\")\n assert Money(\"3.30\") - Money(\"0.03\") == Money(\"3.27\")\n assert Money(\"10.00\") * 3 == Money(\"30.00\")\n assert Money(\"1.00\") < Money(\"1.01\")\n assert Money(\"0.05\").cents() == 5\n assert Money(\"123.45\").cents() == 12345\n assert Money(\"2.50\") == Money(\"2.5\")\n assert hash(Money(\"2.50\")) == hash(Money(\"2.50\"))\n\n\ndef t_adjustment_records():\n result = run_payroll(\n Money(\"300.00\"), [Department(\"eng\", 1), Department(\"ops\", 2)]\n )\n names = [a.department for a in result.adjustments]\n assert names == [\"eng\", \"ops\"], names\n amounts = [a.amount for a in result.adjustments]\n assert amounts == [Money(\"100.00\"), Money(\"200.00\")], amounts\n\n\ndef t_reconcile_basic():\n adjs = [\n type(\"A\", (), {\"amount\": Money(\"33.33\")})(),\n type(\"A\", (), {\"amount\": Money(\"33.33\")})(),\n type(\"A\", (), {\"amount\": Money(\"33.34\")})(),\n ]\n rep = reconcile(adjs, Money(\"100.00\"))\n assert rep[\"balanced\"] is True, rep\n assert rep[\"difference_cents\"] == 0, rep\n bad = [type(\"A\", (), {\"amount\": Money(\"33.33\")})() for _ in range(3)]\n rep2 = reconcile(bad, Money(\"100.00\"))\n assert rep2[\"balanced\"] is False, rep2\n assert rep2[\"difference_cents\"] == -1, rep2\n\n\ndef t_spec_parsing():\n spec = json.dumps({\n \"pool\": \"900.00\",\n \"departments\": [\n {\"name\": \"eng\", \"headcount\": 2},\n {\"name\": \"sales\", \"headcount\": 1},\n ],\n })\n result = load_spec(spec)\n assert result.reconciled is True, result\n assert [a.amount for a in result.adjustments] == [\n Money(\"600.00\"), Money(\"300.00\")\n ]\n\n\ndef main():\n check(\"money::split_evenly_conserves_total\", t_split_conserves_total)\n check(\"money::allocate_conserves_total\", t_allocate_conserves_total)\n check(\"money::half_cent_rounds_half_up\", t_half_cent_rounds_half_up)\n check(\"payroll::run_payroll_reconciles\", t_run_payroll_reconciles)\n check(\"money::parse_and_format\", t_parse_and_format)\n check(\"money::of_cents_and_arithmetic\", t_of_cents_and_arithmetic)\n check(\"payroll::adjustment_records\", t_adjustment_records)\n check(\"report::reconcile_basic\", t_reconcile_basic)\n check(\"loader::spec_parsing\", t_spec_parsing)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/ledger/money.py\n+++ b/ledger/money.py\n@@ -1,65 +1,86 @@\n \"\"\"Monetary amounts and proportional allocation.\n \n-Amounts are stored as floats. Display and storage rounding use the built-in\n-round(), which is round-half-to-even (\"banker's rounding\").\n+Amounts are exact decimal values quantized to cents on construction; rounding\n+is round-half-up (the accounting convention). Allocation happens in integer\n+cents: floors first, then the leftover cents are handed out by descending\n+fractional remainder, so the parts always sum exactly to the amount.\n \"\"\"\n \n from __future__ import annotations\n \n-CENT = 0.01\n+from decimal import Decimal, InvalidOperation, ROUND_HALF_UP\n+\n+CENT = Decimal(\"0.01\")\n \n \n class MoneyError(ValueError):\n \"\"\"Invalid money input (unparsable text, bad allocation weights).\"\"\"\n \n \n-def parse_money(text: str) -> float:\n- \"\"\"Parse a display string like \"$1,234.56\" into a float amount.\"\"\"\n+def parse_money(text: str) -> Decimal:\n+ \"\"\"Parse a display string like \"$1,234.56\" into an exact Decimal.\"\"\"\n if not isinstance(text, str):\n raise MoneyError(f\"cannot parse money from {type(text).__name__}\")\n cleaned = text.strip().lstrip(\"$\").replace(\",\", \"\").replace(\" \", \"\")\n if not cleaned:\n raise MoneyError(\"empty money string\")\n try:\n- return float(cleaned)\n- except ValueError as exc:\n+ value = Decimal(cleaned)\n+ except (InvalidOperation, ValueError) as exc:\n raise MoneyError(f\"invalid money string: {text!r}\") from exc\n+ if not value.is_finite():\n+ raise MoneyError(f\"non-finite money value: {text!r}\")\n+ return value\n+\n+\n+def _to_decimal(amount) -> Decimal:\n+ if isinstance(amount, Money):\n+ return amount.amount\n+ if isinstance(amount, Decimal):\n+ return amount\n+ if isinstance(amount, str):\n+ return parse_money(amount)\n+ if isinstance(amount, int):\n+ return Decimal(amount)\n+ if isinstance(amount, float):\n+ return Decimal(str(amount))\n+ raise MoneyError(f\"unsupported money type: {type(amount).__name__}\")\n \n \n class Money:\n __slots__ = (\"amount\",)\n \n def __init__(self, amount) -> None:\n- if isinstance(amount, Money):\n- self.amount = amount.amount\n- elif isinstance(amount, str):\n- self.amount = round(parse_money(amount), 2)\n- else:\n- self.amount = round(float(amount), 2)\n+ self.amount = _to_decimal(amount).quantize(CENT, rounding=ROUND_HALF_UP)\n \n @classmethod\n def of_cents(cls, cents: int) -> \"Money\":\n- return cls(round(cents / 100.0, 2))\n+ return cls(Decimal(int(cents)).scaleb(-2))\n \n def cents(self) -> int:\n- return int(round(self.amount * 100))\n+ return int(self.amount.scaleb(2))\n \n def __add__(self, other: \"Money\") -> \"Money\":\n if not isinstance(other, Money):\n return NotImplemented\n- return Money(round(self.amount + other.amount, 2))\n+ return Money(self.amount + other.amount)\n \n def __sub__(self, other: \"Money\") -> \"Money\":\n if not isinstance(other, Money):\n return NotImplemented\n- return Money(round(self.amount - other.amount, 2))\n+ return Money(self.amount - other.amount)\n \n- def __mul__(self, factor: float) -> \"Money\":\n- return Money(round(self.amount * float(factor), 2))\n+ def __mul__(self, factor) -> \"Money\":\n+ return Money(self.amount * _to_decimal(factor))\n \n def __eq__(self, other) -> bool:\n if isinstance(other, Money):\n return self.amount == other.amount\n+ if isinstance(other, (Decimal, int, str)):\n+ try:\n+ return self.amount == _to_decimal(other)\n+ except MoneyError:\n+ return NotImplemented\n return NotImplemented\n \n def __lt__(self, other: \"Money\") -> bool:\n@@ -71,23 +92,43 @@\n return hash(self.amount)\n \n def __repr__(self) -> str:\n- return f\"Money({self.amount!r})\"\n+ return f\"Money({str(self.amount)!r})\"\n \n def __str__(self) -> str:\n return f\"${self.amount:,.2f}\"\n \n def split_evenly(self, n: int) -> list[\"Money\"]:\n- \"\"\"Split into n parts. Each part is the same rounded share.\"\"\"\n+ \"\"\"Split into n parts that sum exactly to self (integer cents).\"\"\"\n if n < 1:\n raise MoneyError(\"cannot split into fewer than 1 part\")\n- share = round(self.amount / n, 2)\n- return [Money(share) for _ in range(n)]\n+ total_cents = self.cents()\n+ base, rem = divmod(total_cents, n)\n+ # divmod floors toward negative infinity, so negative pools keep the\n+ # deficit on the first parts and the sum stays exact.\n+ return [Money.of_cents(base + (1 if i < rem else 0)) for i in range(n)]\n \n def allocate(self, weights: list[int]) -> list[\"Money\"]:\n- \"\"\"Allocate proportionally to integer weights.\"\"\"\n+ \"\"\"Allocate proportionally to integer weights (largest remainder).\"\"\"\n if not weights:\n return []\n+ if any(w < 0 for w in weights):\n+ raise MoneyError(\"weights must be non-negative\")\n total = sum(weights)\n if total <= 0:\n raise MoneyError(\"weights must be positive in total\")\n- return [Money(round(self.amount * w / total, 2)) for w in weights]\n+ total_cents = self.cents()\n+ # Exact fractional shares in units of cents/weight-total.\n+ scaled = [total_cents * w for w in weights]\n+ parts = [s // total for s in scaled]\n+ remainders = [s - p * total for s, p in zip(scaled, parts)]\n+ left = total_cents - sum(parts)\n+ if left:\n+ step = 1 if left > 0 else -1\n+ # Ties go to the earlier weight (stable order by remainder, index).\n+ order = sorted(\n+ range(len(weights)),\n+ key=lambda i: (-remainders[i] if step > 0 else remainders[i], i),\n+ )\n+ for k in range(abs(left)):\n+ parts[order[k % len(order)]] += step\n+ return [Money.of_cents(c) for c in parts]\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["money::split_evenly_conserves_total", "money::allocate_conserves_total", "money::half_cent_rounds_half_up", "payroll::run_payroll_reconciles"], "pass_to_pass": ["money::parse_and_format", "money::of_cents_and_arithmetic", "payroll::adjustment_records", "report::reconcile_basic", "loader::spec_parsing"], "time_limit_s": 120, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "py-dst-fold", "title": "Daily scheduler double-fires jobs during DST fall-back", "language": "python", "category": "datetime-semantics", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Scheduler sends the nightly job twice on DST fall-back day\n\n## Summary\n\nOur daily job scheduler fired the 01:30 report twice on November 1, 2026 in\nthe America/New_York zone: once at 01:30 EDT and again at 01:30 EST, one hour\nlater in wall-clock terms but the same wall time. The nightly batch ran\ntwice, duplicating every email.\n\nThe scheduler walks the UTC timeline minute by minute, converts each instant\nto local wall time, and fires whenever the wall clock matches the schedule.\nIts \"already fired\" bookkeeping remembers only the last (hour, minute) pair\nit fired. During a fall-back transition the wall clock repeats an hour, so\nthe pair it saw just before the repeat (01:29) differs from the repeated\ntarget (01:30), and the second occurrence of the target slips through.\n\n## Specification (fire-once per local wall time)\n\n- A job scheduled at HH:MM fires exactly once per local calendar day on which\n that wall time exists.\n- During a fall-back transition, when HH:MM occurs twice, only the FIRST\n occurrence (fold=0) fires.\n- During a spring-forward gap, when HH:MM does not exist, the job does not\n fire that day at all.\n- The returned fire times are UTC instants.\n\n## Environment\n\n- Python 3.11+ with zoneinfo (tzdata required in the runtime image)\n- Code layout: `scheduler/` package (cron, engine, zones)\n\n## Reproduction\n\n```python\nfrom datetime import datetime, timezone\nfrom zoneinfo import ZoneInfo\nfrom scheduler.cron import CronSpec\nfrom scheduler.engine import Scheduler\n\nsched = Scheduler(\"America/New_York\")\nspec = CronSpec.parse(\"01:30\")\nstart = datetime(2026, 10, 31, 0, 0, tzinfo=timezone.utc)\nend = datetime(2026, 11, 2, 0, 0, tzinfo=timezone.utc)\nfires = sched.fire_times(spec, start, end)\nprint(len(fires), [f.isoformat() for f in fires])\n# expected: 2 (Oct 31 05:30Z, Nov 1 05:30Z)\n# actual (buggy): 3 (the second Nov 1 occurrence, 06:30Z, is added)\n```\n\n## Constraints\n\n- `Scheduler.fire_times` and `CronSpec` public APIs stay stable.\n- Minute-by-minute iteration strategy can change; the returned instants and\n their count must match the specification above.", "repo_files": [{"filename": "scheduler/__init__.py", "content": "\"\"\"Daily wall-clock job scheduler.\"\"\"\n"}, {"filename": "scheduler/cron.py", "content": "\"\"\"Schedule specification: a daily job at a fixed local wall-clock time.\"\"\"\n\nfrom __future__ import annotations\n\n\nclass CronError(ValueError):\n \"\"\"Raised for malformed schedule specifications.\"\"\"\n\n\nclass CronSpec:\n \"\"\"A daily schedule at HH:MM local wall time.\"\"\"\n\n def __init__(self, hour: int, minute: int) -> None:\n if not (isinstance(hour, int) and isinstance(minute, int)):\n raise CronError(\"hour and minute must be integers\")\n if isinstance(hour, bool) or isinstance(minute, bool):\n raise CronError(\"hour and minute must be integers\")\n if not (0 <= hour <= 23):\n raise CronError(f\"hour {hour} outside 0..23\")\n if not (0 <= minute <= 59):\n raise CronError(f\"minute {minute} outside 0..59\")\n self.hour = hour\n self.minute = minute\n\n @classmethod\n def parse(cls, text: str) -> \"CronSpec\":\n \"\"\"Parse \"HH:MM\".\"\"\"\n if not isinstance(text, str):\n raise CronError(\"spec must be a string\")\n parts = text.strip().split(\":\")\n if len(parts) != 2:\n raise CronError(f\"invalid spec {text!r}, expected HH:MM\")\n try:\n hour, minute = int(parts[0]), int(parts[1])\n except ValueError as exc:\n raise CronError(f\"invalid spec {text!r}\") from exc\n return cls(hour, minute)\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, CronSpec):\n return NotImplemented\n return (self.hour, self.minute) == (other.hour, other.minute)\n\n def __hash__(self) -> int:\n return hash((self.hour, self.minute))\n\n def __str__(self) -> str:\n return f\"{self.hour:02d}:{self.minute:02d}\"\n\n def __repr__(self) -> str:\n return f\"CronSpec({self.hour:02d}:{self.minute:02d})\"\n"}, {"filename": "scheduler/engine.py", "content": "\"\"\"Firing engine.\n\nWalks the UTC timeline one minute at a time and fires whenever the local\nwall clock matches the schedule. Bookkeeping remembers the most recent wall\n(hour, minute) pair that was examined, so a repeated wall time on a\nfall-back day looks like a new target.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom datetime import datetime, timedelta\n\nfrom .cron import CronSpec\nfrom .zones import get_zone\n\nMINUTE = timedelta(minutes=1)\n\n\nclass Scheduler:\n def __init__(self, tz_name: str) -> None:\n self.tz_name = tz_name\n self.zone = get_zone(tz_name)\n\n def fire_times(self, spec: CronSpec, start_utc: datetime, end_utc: datetime):\n \"\"\"Return the UTC instants in [start_utc, end_utc] on which spec fires.\"\"\"\n if start_utc.tzinfo is None or end_utc.tzinfo is None:\n raise ValueError(\"start and end must be timezone-aware\")\n if end_utc < start_utc:\n raise ValueError(\"end must not be before start\")\n fires = []\n last_seen = None # most recently examined wall (hour, minute) pair\n instant = start_utc\n while instant <= end_utc:\n local = instant.astimezone(self.zone)\n key = (local.hour, local.minute)\n if key == (spec.hour, spec.minute) and key != last_seen:\n fires.append(instant)\n last_seen = key\n instant += MINUTE\n return fires\n"}, {"filename": "scheduler/zones.py", "content": "\"\"\"Time zone helpers.\"\"\"\n\nfrom __future__ import annotations\n\nfrom datetime import datetime, timezone\nfrom zoneinfo import ZoneInfo\n\nSUPPORTED_ZONES = (\n \"UTC\",\n \"America/New_York\",\n \"Europe/Berlin\",\n \"Asia/Kolkata\",\n \"Australia/Sydney\",\n \"America/Sao_Paulo\",\n)\n\n\ndef get_zone(name: str) -> ZoneInfo:\n if name not in SUPPORTED_ZONES:\n raise ValueError(f\"unsupported zone {name!r}\")\n return ZoneInfo(name)\n\n\ndef wall_key(instant: datetime, zone: ZoneInfo):\n \"\"\"The (date, hour, minute) wall-clock identity of an instant.\"\"\"\n local = instant.astimezone(zone)\n return (local.date(), local.hour, local.minute)\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport os\nimport sys\nfrom datetime import datetime, timezone\nfrom zoneinfo import ZoneInfo\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.dirname(HERE))\n\nfrom scheduler.cron import CronSpec, CronError\nfrom scheduler.engine import Scheduler\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\nNY = ZoneInfo(\"America/New_York\")\nUTC = timezone.utc\n\n\ndef local(y, mo, d, h, mi, zone=NY, fold=0):\n return datetime(y, mo, d, h, mi, tzinfo=zone, fold=fold)\n\n\ndef t_fall_back_fires_once():\n sched = Scheduler(\"America/New_York\")\n spec = CronSpec.parse(\"01:30\")\n start = datetime(2026, 10, 31, 0, 0, tzinfo=UTC)\n end = datetime(2026, 11, 2, 0, 0, tzinfo=UTC)\n fires = sched.fire_times(spec, start, end)\n # Oct 31 01:30 EDT and Nov 1 01:30 EDT (first occurrence, fold=0).\n expected = [\n local(2026, 10, 31, 1, 30).astimezone(UTC),\n local(2026, 11, 1, 1, 30).astimezone(UTC),\n ]\n assert len(fires) == 2, f\"expected 2 fires, got {len(fires)}: {fires}\"\n assert fires == expected, f\"{fires} != {expected}\"\n # the second (EST) occurrence of 01:30 must NOT fire\n second = local(2026, 11, 1, 1, 30, fold=1).astimezone(UTC)\n assert second not in fires, f\"second occurrence {second} must not fire\"\n\n\ndef t_fire_instants_exact_multi_day():\n # A fire time inside the repeated fall-back hour: wall time 01:30 occurs\n # twice on Nov 1 (01:30 EDT, then 01:30 EST). Only the first occurrence\n # may fire, so a multi-day window yields exactly one fire per local date\n # with exact UTC instants (05:30Z before the transition, 06:30Z after).\n sched = Scheduler(\"America/New_York\")\n spec = CronSpec.parse(\"01:30\")\n start = datetime(2026, 10, 30, 0, 0, tzinfo=UTC)\n end = datetime(2026, 11, 2, 23, 59, tzinfo=UTC)\n fires = sched.fire_times(spec, start, end)\n expected = [\n local(2026, 10, 30, 1, 30).astimezone(UTC),\n local(2026, 10, 31, 1, 30).astimezone(UTC),\n local(2026, 11, 1, 1, 30).astimezone(UTC),\n local(2026, 11, 2, 1, 30).astimezone(UTC),\n ]\n assert len(fires) == 4, f\"expected 4 fires, got {len(fires)}: {fires}\"\n assert fires == expected, f\"{fires} != {expected}\"\n second = local(2026, 11, 1, 1, 30, fold=1).astimezone(UTC)\n assert second not in fires, f\"second occurrence {second} must not fire\"\n\n\ndef t_normal_days_one_fire_each():\n sched = Scheduler(\"America/New_York\")\n spec = CronSpec.parse(\"12:00\")\n start = datetime(2026, 10, 25, 0, 0, tzinfo=UTC)\n end = datetime(2026, 10, 27, 23, 59, tzinfo=UTC)\n fires = sched.fire_times(spec, start, end)\n expected = [local(2026, 10, d, 12, 0).astimezone(UTC) for d in (25, 26, 27)]\n assert fires == expected, f\"{fires} != {expected}\"\n\n\ndef t_spring_gap_no_fire():\n sched = Scheduler(\"America/New_York\")\n spec = CronSpec.parse(\"02:30\") # does not exist on Mar 8, 2026\n start = datetime(2026, 3, 8, 0, 0, tzinfo=UTC)\n end = datetime(2026, 3, 8, 23, 59, tzinfo=UTC)\n fires = sched.fire_times(spec, start, end)\n assert fires == [], f\"02:30 does not exist on the gap day, got {fires}\"\n # 01:30 exists before the gap and must still fire\n spec_ok = CronSpec.parse(\"01:30\")\n fires_ok = sched.fire_times(spec_ok, start, end)\n assert len(fires_ok) == 1, fires_ok\n\n\ndef t_non_dst_zone_daily():\n sched = Scheduler(\"Asia/Kolkata\")\n spec = CronSpec.parse(\"09:15\")\n start = datetime(2026, 10, 25, 0, 0, tzinfo=UTC)\n end = datetime(2026, 10, 27, 23, 59, tzinfo=UTC)\n fires = sched.fire_times(spec, start, end)\n expected = [local(2026, 10, d, 9, 15, zone=ZoneInfo(\"Asia/Kolkata\")).astimezone(UTC) for d in (25, 26, 27)]\n assert fires == expected, f\"{fires} != {expected}\"\n\n\ndef t_range_bounds_inclusive():\n sched = Scheduler(\"UTC\")\n spec = CronSpec.parse(\"00:00\")\n start = datetime(2026, 10, 25, 0, 0, tzinfo=UTC)\n end = datetime(2026, 10, 27, 0, 0, tzinfo=UTC)\n fires = sched.fire_times(spec, start, end)\n assert fires == [start, datetime(2026, 10, 26, 0, 0, tzinfo=UTC), end], fires\n\n\ndef t_cron_parse_and_validate():\n assert CronSpec.parse(\"00:00\") == CronSpec(0, 0)\n assert CronSpec.parse(\"23:59\") == CronSpec(23, 59)\n assert str(CronSpec(1, 5)) == \"01:05\"\n assert CronSpec.parse(\" 07:05 \") == CronSpec(7, 5)\n for bad in [\"24:00\", \"12:60\", \"abc\", \"1:2:3\", \"\", \"12:\", \":30\", \"-1:00\", \"12:00:00\"]:\n try:\n CronSpec.parse(bad)\n except CronError:\n continue\n raise AssertionError(f\"{bad!r} must be rejected\")\n for bad in [(24, 0), (0, 60), (-1, 0), (0, -1)]:\n try:\n CronSpec(*bad)\n except CronError:\n continue\n raise AssertionError(f\"{bad} must be rejected\")\n\n\ndef main():\n check(\"schedule::fall_back_fires_once\", t_fall_back_fires_once)\n check(\"schedule::fire_instants_exact_multi_day\", t_fire_instants_exact_multi_day)\n check(\"schedule::normal_days_one_fire_each\", t_normal_days_one_fire_each)\n check(\"schedule::spring_gap_no_fire\", t_spring_gap_no_fire)\n check(\"schedule::non_dst_zone_daily\", t_non_dst_zone_daily)\n check(\"schedule::range_bounds_inclusive\", t_range_bounds_inclusive)\n check(\"cron::parse_and_validate\", t_cron_parse_and_validate)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/scheduler/engine.py\n+++ b/scheduler/engine.py\n@@ -1,9 +1,11 @@\n \"\"\"Firing engine.\n \n Walks the UTC timeline one minute at a time and fires whenever the local\n-wall clock matches the schedule. Bookkeeping remembers the most recent wall\n-(hour, minute) pair that was examined, so a repeated wall time on a\n-fall-back day looks like a new target.\n+wall clock matches the schedule. The \"already fired\" bookkeeping keys on the\n+full wall identity (local date, hour, minute): during a fall-back transition\n+the repeated hour maps to the same key as its first occurrence, so the\n+second occurrence is correctly suppressed. A spring-forward gap simply never\n+produces a matching wall time, so nothing fires.\n \"\"\"\n \n from __future__ import annotations\n@@ -28,13 +30,14 @@\n if end_utc < start_utc:\n raise ValueError(\"end must not be before start\")\n fires = []\n- last_seen = None # most recently examined wall (hour, minute) pair\n+ fired = set() # wall identities (date, hour, minute) already fired\n instant = start_utc\n while instant <= end_utc:\n local = instant.astimezone(self.zone)\n- key = (local.hour, local.minute)\n- if key == (spec.hour, spec.minute) and key != last_seen:\n- fires.append(instant)\n- last_seen = key\n+ if (local.hour, local.minute) == (spec.hour, spec.minute):\n+ key = (local.date(), local.hour, local.minute)\n+ if key not in fired:\n+ fired.add(key)\n+ fires.append(instant)\n instant += MINUTE\n return fires\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["schedule::fall_back_fires_once", "schedule::fire_instants_exact_multi_day"], "pass_to_pass": ["schedule::normal_days_one_fire_each", "schedule::spring_gap_no_fire", "schedule::non_dst_zone_daily", "schedule::range_bounds_inclusive", "cron::parse_and_validate"], "time_limit_s": 60, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": ["tzdata"]} {"task_id": "py-regex-redos", "title": "Module path validator hangs on malformed input (catastrophic backtracking)", "language": "python", "category": "algorithmic-complexity", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Module path validation hangs on malformed input\n\n## Summary\n\nThe log filter validates the module field of every log line with a regular\nexpression. A single malformed line containing a long run of identifier\ncharacters followed by an invalid character makes `is_module_path` hang for\nminutes. The log ingestion worker blocks, the pipeline backs up, and the\nprocess has to be killed.\n\nThe validator must accept exactly the same language as before (so all\nexisting log lines keep passing), but in time linear in the input length.\n\n## Environment\n\n- Python 3.11+, no third-party dependencies\n- Code layout: `logfilter/` package (patterns, pipeline)\n\n## Reproduction\n\n```python\nimport time\nfrom logfilter.patterns import is_module_path\n\npayload = \"a\" * 28 + \"!\"\nt0 = time.perf_counter()\nprint(is_module_path(payload))\nprint(f\"elapsed: {time.perf_counter() - t0:.3f}s\")\n```\n\nExpected: `False` in well under 0.1 s for any input (linear matching).\n\nActual (buggy): the call takes minutes and scales exponentially with the\nlength of the run of word characters.\n\n## Specification of the language (must be preserved exactly)\n\nA module path is a non-empty sequence of segments. Each segment consists of\none leading ASCII letter or underscore, followed by zero or more word\ncharacters (letters, digits, underscore; Unicode word characters included),\nfollowed by an optional single dot. Accept: `auth`, `auth.service.oauth`,\n`a`, `a_b.c1`, `trailing.`. Reject: the empty string, `auth..svc`,\n`.auth`, `a b`, `a-b`.\n\n## Constraints\n\n- `is_module_path(text)` signature and accepted language must not change.\n- Matching must be linear in the size of the input for all inputs, including\n adversarial ones.\n- `logfilter/pipeline.py` must keep working unchanged in behavior.", "repo_files": [{"filename": "logfilter/__init__.py", "content": "\"\"\"Log filtering utilities.\"\"\"\n"}, {"filename": "logfilter/patterns.py", "content": "\"\"\"Module-path matching for the log filter DSL.\n\nA module path is a sequence of dotted segments. Each segment starts with an\nASCII letter or underscore, continues with word characters and may end with\na single dot.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\n\n# One segment: leading letter or underscore, word characters, optional dot.\nSEGMENT_RE = re.compile(r\"[a-zA-Z_]\\w*\\.?\")\n\n# Full validation of a module path.\nMODULE_RE = re.compile(r\"^(?:[a-zA-Z_]\\w*\\.?)*$\")\n\n\ndef is_module_path(text: str) -> bool:\n \"\"\"Return True if text is a valid module path.\"\"\"\n if not isinstance(text, str):\n return False\n return MODULE_RE.match(text) is not None\n"}, {"filename": "logfilter/pipeline.py", "content": "\"\"\"Apply module filters to raw log lines.\n\nLog line format: timestamp, level, module, message, separated by tabs.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom .patterns import is_module_path\n\n\ndef parse_line(line: str) -> dict | None:\n parts = line.rstrip(\"\\n\").split(\"\\t\")\n if len(parts) < 4:\n return None\n return {\n \"timestamp\": parts[0],\n \"level\": parts[1],\n \"module\": parts[2],\n \"message\": \"\\t\".join(parts[3:]),\n }\n\n\ndef valid_lines(lines):\n \"\"\"Yield parsed records whose module field is a valid module path.\"\"\"\n for line in lines:\n record = parse_line(line)\n if record is None:\n continue\n if is_module_path(record[\"module\"]):\n yield record\n\n\ndef filter_lines(lines, module_name: str):\n \"\"\"Yield parsed records for one specific module.\"\"\"\n for record in valid_lines(lines):\n if record[\"module\"] == module_name:\n yield record\n"}], "test_files": [{"filename": "_perf.py", "content": "\"\"\"Isolated perf probe: validate one payload, print JSON with timing.\"\"\"\n\nimport json\nimport os\nimport sys\nimport time\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom logfilter.patterns import is_module_path\n\n\ndef main():\n payload = sys.argv[1]\n start = time.perf_counter()\n result = is_module_path(payload)\n elapsed = time.perf_counter() - start\n print(json.dumps({\"result\": result, \"elapsed\": elapsed}))\n\n\nif __name__ == \"__main__\":\n main()\n"}, {"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport os\nimport subprocess\nimport sys\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.dirname(HERE))\n\nfrom logfilter.patterns import is_module_path\nfrom logfilter.pipeline import filter_lines, parse_line\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\nPERF_BUDGET_S = 2.5\n\n\ndef probe(payload: str) -> tuple[bool, float]:\n \"\"\"Run the validator in a subprocess so a hang cannot stall the suite.\"\"\"\n proc = subprocess.run(\n [sys.executable, os.path.join(HERE, \"_perf.py\"), payload],\n capture_output=True,\n text=True,\n timeout=PERF_BUDGET_S,\n cwd=os.path.dirname(HERE),\n )\n import json\n\n data = json.loads(proc.stdout.strip().splitlines()[-1])\n return bool(data[\"result\"]), float(data[\"elapsed\"])\n\n\ndef t_adversarial_input_fast():\n payload = \"a\" * 28 + \"!\"\n try:\n result, elapsed = probe(payload)\n except subprocess.TimeoutExpired:\n raise AssertionError(\n f\"validator did not finish within {PERF_BUDGET_S}s on adversarial input\"\n )\n assert result is False, f\"payload must be rejected, got {result!r}\"\n assert elapsed < 2.0, f\"validation took {elapsed:.2f}s (must be linear)\"\n\n\ndef t_longer_adversarial_input_fast():\n payload = \"b_9\" * 14 + \"!\"\n try:\n result, elapsed = probe(payload)\n except subprocess.TimeoutExpired:\n raise AssertionError(\n f\"validator did not finish within {PERF_BUDGET_S}s on adversarial input\"\n )\n assert result is False, f\"payload must be rejected, got {result!r}\"\n assert elapsed < 2.0, f\"validation took {elapsed:.2f}s (must be linear)\"\n\n\ndef t_empty_string_rejected():\n assert is_module_path(\"\") is False, \"empty string is not a module path\"\n\n\ndef t_valid_module_names():\n valid = [\n \"auth\",\n \"auth.service\",\n \"auth.service.oauth\",\n \"a\",\n \"_\",\n \"_private.mod\",\n \"a_b.c1\",\n \"trailing.\",\n \"a.\",\n \"a1.b2.c3\",\n \"Module123\",\n \"a\\u00e9.b\", # Unicode word characters are allowed after the first\n ]\n for name in valid:\n assert is_module_path(name) is True, f\"{name!r} must be accepted\"\n\n\ndef t_invalid_names_rejected():\n invalid = [\n \"auth..svc\",\n \".auth\",\n \"a b\",\n \"a-b\",\n \".a\",\n \"..\",\n \"a..b\",\n \"a.\\u00e9..b\",\n \"a\\tb\",\n ]\n for name in invalid:\n assert is_module_path(name) is False, f\"{name!r} must be rejected\"\n\n\ndef t_long_valid_name_linear():\n name = \"seg\" * 200 + \".end\"\n assert is_module_path(name) is True\n deep = \".\".join(\"s\" * 50 for _ in range(50))\n assert is_module_path(deep) is True\n\n\ndef t_filters_log_lines():\n lines = [\n \"2026-10-13T00:00:00Z\\tINFO\\tauth.login\\tuser signed in\",\n \"2026-10-13T00:00:01Z\\tWARN\\tauth..bad\\tmalformed module\",\n \"2026-10-13T00:00:02Z\\tINFO\\tauth.logout\\tuser signed out\",\n \"not-a-log-line\",\n ]\n got = list(filter_lines(lines, \"auth.login\"))\n assert len(got) == 1, got\n assert got[0][\"message\"] == \"user signed in\", got\n assert parse_line(lines[1])[\"module\"] == \"auth..bad\"\n\n\ndef main():\n check(\"patterns::adversarial_input_fast\", t_adversarial_input_fast)\n check(\"patterns::longer_adversarial_input_fast\", t_longer_adversarial_input_fast)\n check(\"patterns::empty_string_rejected\", t_empty_string_rejected)\n check(\"patterns::valid_module_names\", t_valid_module_names)\n check(\"patterns::invalid_names_rejected\", t_invalid_names_rejected)\n check(\"patterns::long_valid_name_linear\", t_long_valid_name_linear)\n check(\"pipeline::filters_log_lines\", t_filters_log_lines)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/logfilter/patterns.py\n+++ b/logfilter/patterns.py\n@@ -3,21 +3,43 @@\n A module path is a sequence of dotted segments. Each segment starts with an\n ASCII letter or underscore, continues with word characters and may end with\n a single dot.\n+\n+The previous implementation used the pattern\n+``^(?:[a-zA-Z_]\\\\w*\\\\.?)*$``. Because the inner ``\\w*`` and the outer group can\n+both consume the same characters in many different ways, a non-matching input\n+(e.g. a long run of word characters followed by an invalid byte) forces the\n+engine to explore exponentially many decompositions before it can report\n+failure. The matcher below is equivalent but linear: each iteration consumes\n+at least one character, and the per-segment pattern has no nested\n+quantifiers, so the scan visits each position a constant number of times.\n \"\"\"\n \n from __future__ import annotations\n \n import re\n \n-# One segment: leading letter or underscore, word characters, optional dot.\n+# One segment: leading ASCII letter or underscore, word characters, optional\n+# single trailing dot. No nested quantifiers: safe to apply at each position.\n SEGMENT_RE = re.compile(r\"[a-zA-Z_]\\w*\\.?\")\n-\n-# Full validation of a module path.\n-MODULE_RE = re.compile(r\"^(?:[a-zA-Z_]\\w*\\.?)*$\")\n \n \n def is_module_path(text: str) -> bool:\n- \"\"\"Return True if text is a valid module path.\"\"\"\n- if not isinstance(text, str):\n+ \"\"\"Return True if text is a valid module path.\n+\n+ A module path is a non-empty sequence of segments. Each iteration of the\n+ loop consumes one full segment (at least one character), so the whole\n+ match runs in time linear in len(text).\n+ \"\"\"\n+ if not isinstance(text, str) or not text:\n return False\n- return MODULE_RE.match(text) is not None\n+ pos = 0\n+ length = len(text)\n+ while pos < length:\n+ match = SEGMENT_RE.match(text, pos)\n+ if match is None:\n+ return False\n+ end = match.end()\n+ if end == pos: # defensive: never happens, SEGMENT_RE consumes >= 1\n+ return False\n+ pos = end\n+ return True\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["patterns::adversarial_input_fast", "patterns::longer_adversarial_input_fast", "patterns::empty_string_rejected"], "pass_to_pass": ["patterns::valid_module_names", "patterns::invalid_names_rejected", "patterns::long_valid_name_linear", "pipeline::filters_log_lines"], "time_limit_s": 120, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "py-unicode-canon", "title": "Tag index creates duplicate entries for visually identical tags", "language": "python", "category": "unicode-semantics", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Tag index fragments visually identical tags into duplicate entries\n\n## Summary\n\nThe document tag index produces duplicate entries for tags that are visually\nidentical but encoded differently. Searching for a tag with one encoding\nmisses documents that were indexed with another encoding of the same tag.\n\nConcrete failures observed in production data:\n\n- \"cafe\" with a combining acute accent (NFD) indexed separately from the\n precomposed form (NFC).\n- The German word \"Strasse\" typed with a sharp s did not match the same word\n typed with \"SS\".\n- Ligature and full-width forms (\"fi\" ligature, full-width \"ABC\") did not\n match their plain ASCII equivalents.\n\n`index/canonical.py` strips whitespace and lowercases, which handles only\nASCII case. Canonical keys must instead apply Unicode normalization\n(NFKC), the full caseless mapping (casefold, not lower), and removal of\ninvisible format characters, so that all forms of one tag map to one key.\n\n## Environment\n\n- Python 3.11+, no third-party dependencies\n- Code layout: `index/` package (canonical, store, pipeline, report)\n\n## Reproduction\n\n```python\nfrom index.canonical import canonical_key\n\nnfc = \"caf\\u00e9\" # precomposed\nnfd = \"cafe\\u0301\" # combining acute\nprint(canonical_key(nfc) == canonical_key(nfd)) # False (bug)\n\nprint(canonical_key(\"Stra\\u00dfe\") == canonical_key(\"STRASSE\")) # False (bug)\n\nprint(canonical_key(\"\\ufb01le\") == canonical_key(\"file\")) # False (bug)\n```\n\n## Constraints\n\n- `canonical_key` signature stays stable; `TagIndex` and pipeline APIs stay\n stable.\n- Distinct tags must remain distinct: \"cat\" and \"dog\", \"cat\" and \"cats\".\n- Case-insensitivity semantics stay (Cat == cat).", "repo_files": [{"filename": "index/__init__.py", "content": "\"\"\"Document tag indexing.\"\"\"\n"}, {"filename": "index/canonical.py", "content": "\"\"\"Tag canonicalization.\"\"\"\n\nfrom __future__ import annotations\n\n\ndef canonical_key(tag: str) -> str:\n \"\"\"Return the canonical lookup key for a tag.\n\n Tags are matched case-insensitively with surrounding whitespace removed.\n \"\"\"\n if not isinstance(tag, str):\n raise TypeError(f\"tag must be a string, got {type(tag).__name__}\")\n return tag.strip().lower()\n"}, {"filename": "index/pipeline.py", "content": "\"\"\"Document ingestion: split raw tag strings into clean tags.\"\"\"\n\nfrom __future__ import annotations\n\n\ndef split_tags(raw: str) -> list[str]:\n \"\"\"Split a comma-separated tag string, trimming each tag.\"\"\"\n if raw is None:\n return []\n return [part.strip() for part in raw.split(\",\") if part.strip()]\n\n\ndef ingest_document(index, doc: dict) -> None:\n \"\"\"Index one document. A document has \"id\" and \"tags\" (comma separated).\"\"\"\n index.add(doc[\"id\"], split_tags(doc.get(\"tags\", \"\")))\n"}, {"filename": "index/report.py", "content": "\"\"\"Tag reporting.\"\"\"\n\nfrom __future__ import annotations\n\n\ndef tag_counts(index) -> dict:\n \"\"\"Return {tag key: number of documents}.\"\"\"\n return {key: len(docs) for key, docs in sorted(index.items())}\n"}, {"filename": "index/store.py", "content": "\"\"\"In-memory tag index: canonical key -> document ids.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .canonical import canonical_key\n\n\nclass TagIndex:\n def __init__(self) -> None:\n self._by_key: dict[str, set] = {}\n\n def add(self, doc_id, tags) -> None:\n for tag in tags:\n key = canonical_key(tag)\n if not key:\n continue\n self._by_key.setdefault(key, set()).add(doc_id)\n\n def remove(self, doc_id) -> None:\n for docs in self._by_key.values():\n docs.discard(doc_id)\n self._by_key = {k: v for k, v in self._by_key.items() if v}\n\n def find(self, tag) -> set:\n return set(self._by_key.get(canonical_key(tag), ()))\n\n def keys(self) -> set:\n return set(self._by_key)\n\n def items(self):\n return list(self._by_key.items())\n\n def __len__(self) -> int:\n return len(self._by_key)\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport os\nimport sys\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.dirname(HERE))\n\nfrom index.canonical import canonical_key\nfrom index.store import TagIndex\nfrom index.pipeline import ingest_document, split_tags\nfrom index.report import tag_counts\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\nNFC_CAFE = \"caf\\u00e9\" # precomposed\nNFD_CAFE = \"cafe\\u0301\" # combining acute\nSHARP_S = \"Stra\\u00dfe\"\nSS_FORM = \"STRASSE\"\nLIGATURE_FI = \"\\ufb01le\" # fi ligature + le\nFULLWIDTH_ABC = \"\\uff21\\uff22\\uff23\"\nCIRCLED_ONE = \"\\u2460\"\nZWSP_TAG = \"in\\u200bfo\"\n\n\ndef t_nfc_nfd_equivalent():\n assert canonical_key(NFC_CAFE) == canonical_key(NFD_CAFE), (\n f\"{canonical_key(NFC_CAFE)!r} != {canonical_key(NFD_CAFE)!r}\"\n )\n assert canonical_key(NFC_CAFE) == canonical_key(\"CAF\\u00c9\")\n\n\ndef t_casefold_sharp_s():\n assert canonical_key(SHARP_S) == canonical_key(SS_FORM), (\n f\"{canonical_key(SHARP_S)!r} != {canonical_key(SS_FORM)!r}\"\n )\n assert canonical_key(SHARP_S) == canonical_key(\"strasse\")\n\n\ndef t_compatibility_forms():\n assert canonical_key(LIGATURE_FI) == canonical_key(\"file\"), (\n f\"{canonical_key(LIGATURE_FI)!r} != {canonical_key('file')!r}\"\n )\n assert canonical_key(FULLWIDTH_ABC) == canonical_key(\"abc\"), (\n f\"{canonical_key(FULLWIDTH_ABC)!r} != {canonical_key('abc')!r}\"\n )\n assert canonical_key(CIRCLED_ONE) == canonical_key(\"1\"), (\n f\"{canonical_key(CIRCLED_ONE)!r} != {canonical_key('1')!r}\"\n )\n\n\ndef t_zero_width_stripped():\n assert canonical_key(ZWSP_TAG) == canonical_key(\"info\"), (\n f\"{canonical_key(ZWSP_TAG)!r} != {canonical_key('info')!r}\"\n )\n\n\ndef t_lookup_across_forms():\n index = TagIndex()\n ingest_document(index, {\"id\": \"doc-1\", \"tags\": NFD_CAFE})\n ingest_document(index, {\"id\": \"doc-2\", \"tags\": SHARP_S})\n assert index.find(NFC_CAFE) == {\"doc-1\"}, index.find(NFC_CAFE)\n assert index.find(\"cafe\") == set()\n assert index.find(SS_FORM) == {\"doc-2\"}, index.find(SS_FORM)\n assert index.find(\"strasse\") == {\"doc-2\"}\n\n\ndef t_no_duplicate_keys_for_forms():\n index = TagIndex()\n index.add(\"doc-1\", [NFC_CAFE])\n index.add(\"doc-2\", [NFD_CAFE])\n index.add(\"doc-3\", [SHARP_S])\n index.add(\"doc-4\", [SS_FORM])\n assert len(index) == 2, f\"expected 2 canonical keys, got {len(index)}: {index.keys()}\"\n assert index.find(NFC_CAFE) == {\"doc-1\", \"doc-2\"}\n assert index.find(SHARP_S) == {\"doc-3\", \"doc-4\"}\n\n\ndef t_distinct_tags_stay_distinct():\n index = TagIndex()\n index.add(\"d1\", [\"cat\"])\n index.add(\"d2\", [\"dog\"])\n index.add(\"d3\", [\"cats\"])\n assert len(index) == 3, index.keys()\n assert index.find(\"cat\") == {\"d1\"}\n assert index.find(\"cats\") == {\"d3\"}\n\n\ndef t_comma_split_and_trim():\n assert split_tags(\"a, b ,c\") == [\"a\", \"b\", \"c\"]\n assert split_tags(\"solo\") == [\"solo\"]\n assert split_tags(\"\") == []\n assert split_tags(\" \") == []\n\n\ndef t_empty_tags_ignored():\n index = TagIndex()\n ingest_document(index, {\"id\": \"doc-1\", \"tags\": \"a,,b,\"})\n assert index.find(\"a\") == {\"doc-1\"}\n assert index.find(\"b\") == {\"doc-1\"}\n ingest_document(index, {\"id\": \"doc-2\", \"tags\": \"\"})\n ingest_document(index, {\"id\": \"doc-3\", \"tags\": \" \"})\n assert len(index) == 2\n\n\ndef t_tag_counts():\n index = TagIndex()\n ingest_document(index, {\"id\": \"d1\", \"tags\": \"alpha,beta\"})\n ingest_document(index, {\"id\": \"d2\", \"tags\": \"alpha\"})\n counts = tag_counts(index)\n assert counts == {\"alpha\": 2, \"beta\": 1}, counts\n\n\ndef t_remove_document():\n index = TagIndex()\n ingest_document(index, {\"id\": \"d1\", \"tags\": \"alpha,beta\"})\n ingest_document(index, {\"id\": \"d2\", \"tags\": \"alpha\"})\n index.remove(\"d1\")\n assert index.find(\"beta\") == set()\n assert index.find(\"alpha\") == {\"d2\"}\n\n\ndef main():\n check(\"canonical::nfc_nfd_equivalent\", t_nfc_nfd_equivalent)\n check(\"canonical::casefold_sharp_s\", t_casefold_sharp_s)\n check(\"canonical::compatibility_forms\", t_compatibility_forms)\n check(\"canonical::zero_width_stripped\", t_zero_width_stripped)\n check(\"index::lookup_across_forms\", t_lookup_across_forms)\n check(\"index::no_duplicate_keys_for_forms\", t_no_duplicate_keys_for_forms)\n check(\"index::distinct_tags_stay_distinct\", t_distinct_tags_stay_distinct)\n check(\"pipeline::comma_split_and_trim\", t_comma_split_and_trim)\n check(\"pipeline::empty_tags_ignored\", t_empty_tags_ignored)\n check(\"report::tag_counts\", t_tag_counts)\n check(\"index::remove_document\", t_remove_document)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/index/canonical.py\n+++ b/index/canonical.py\n@@ -1,13 +1,30 @@\n-\"\"\"Tag canonicalization.\"\"\"\n+\"\"\"Tag canonicalization.\n+\n+A canonical key must be identical for every visual form of a tag:\n+\n+- NFKC normalization folds compatibility forms (ligatures, full-width\n+ characters, circled digits) onto their canonical equivalents and composes\n+ combining-mark sequences.\n+- casefold (not lower) applies the full Unicode caseless mapping, which\n+ includes German sharp s to \"ss\" and other multi-letter folds.\n+- Invisible format and control characters (zero-width joiners, BOM,\n+ directional marks) are removed so they cannot fork the key space.\n+\"\"\"\n \n from __future__ import annotations\n \n+import unicodedata\n+\n+_INVISIBLE_CATEGORIES = frozenset({\"Cf\", \"Cc\", \"Cs\", \"Co\", \"Cn\"})\n+\n \n def canonical_key(tag: str) -> str:\n- \"\"\"Return the canonical lookup key for a tag.\n-\n- Tags are matched case-insensitively with surrounding whitespace removed.\n- \"\"\"\n+ \"\"\"Return the canonical lookup key for a tag.\"\"\"\n if not isinstance(tag, str):\n raise TypeError(f\"tag must be a string, got {type(tag).__name__}\")\n- return tag.strip().lower()\n+ normalized = unicodedata.normalize(\"NFKC\", tag)\n+ folded = normalized.casefold()\n+ cleaned = \"\".join(\n+ ch for ch in folded if unicodedata.category(ch) not in _INVISIBLE_CATEGORIES\n+ )\n+ return cleaned.strip()\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["canonical::nfc_nfd_equivalent", "canonical::casefold_sharp_s", "canonical::compatibility_forms", "canonical::zero_width_stripped", "index::lookup_across_forms", "index::no_duplicate_keys_for_forms"], "pass_to_pass": ["index::distinct_tags_stay_distinct", "pipeline::comma_split_and_trim", "pipeline::empty_tags_ignored", "report::tag_counts", "index::remove_document"], "time_limit_s": 60, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "py-validation-bypass", "title": "Settings fast path bypasses descriptor validation on construction", "language": "python", "category": "data-model-semantics", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Out-of-range values from config files are accepted by settings\n\n## Summary\n\nA production config file with `\"timeout_s\": 0` was accepted by the service at\nstartup and the first request hung forever waiting for a socket timeout of\nzero. Direct attribute assignment is validated correctly (`app.port = 80`\nraises), but values loaded from a JSON config file are not.\n\nThe `SettingsBase.__init__` fast path loads keyword overrides directly into\nthe instance dictionary for speed. That skips the `RangeField` descriptors,\nwhose `__set__` performs the range check. Any value that arrives through the\nconstructor or the JSON loader therefore bypasses validation, while the same\nvalue assigned later through the attribute protocol is rejected.\n\n## Environment\n\n- Python 3.11+, no third-party dependencies\n- Code layout: `app/` package (fields, settings, loader, cli)\n\n## Reproduction\n\n```python\nfrom app.loader import load_settings\nfrom app.fields import FieldError\n\ntry:\n load_settings('{\"port\": 99999, \"workers\": 4, \"timeout_s\": 30}')\nexcept FieldError:\n print(\"rejected\")\nelse:\n print(\"ACCEPTED - bug: port 99999 is not a valid port\")\n\ns = load_settings('{\"port\": 8080, \"workers\": 4, \"timeout_s\": 30}')\ns.port = 80 # this raises FieldError, as expected\n```\n\nExpected: every path that produces a settings object enforces the declared\nranges (1024-65535 for port, 1-64 for workers, 1-3600 for timeout_s).\n\n## Constraints\n\n- `RangeField` semantics (descriptor protocol, `__set_name__`, range checks)\n must be preserved.\n- `SettingsBase(**overrides)` signature and `as_dict()` must stay stable.\n- The JSON loader format and `app/cli.py` are not part of the defect.", "repo_files": [{"filename": "app/__init__.py", "content": "\"\"\"Application settings subsystem.\"\"\"\n"}, {"filename": "app/cli.py", "content": "\"\"\"Command line entry point for the service.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\n\nfrom .loader import load_settings\n\n\ndef main(argv: list[str] | None = None) -> int:\n argv = sys.argv[1:] if argv is None else argv\n if len(argv) != 1:\n print(\"usage: service \", file=sys.stderr)\n return 2\n with open(argv[1], \"r\", encoding=\"utf-8\") as handle:\n settings = load_settings(handle.read())\n print(settings.as_dict())\n return 0\n"}, {"filename": "app/fields.py", "content": "\"\"\"Declarative range-checked fields implemented as descriptors.\"\"\"\n\nfrom __future__ import annotations\n\n\nclass FieldError(ValueError):\n \"\"\"Raised for invalid field values or unknown field names.\"\"\"\n\n\nclass RangeField:\n \"\"\"Descriptor that validates values on assignment.\"\"\"\n\n def __init__(self, lo: int, hi: int) -> None:\n self.lo = lo\n self.hi = hi\n self.name: str | None = None\n\n def __set_name__(self, owner: type, name: str) -> None:\n if self.name is None:\n self.name = name\n\n @property\n def storage_name(self) -> str:\n if self.name is None:\n raise FieldError(\"RangeField is not bound to a class yet\")\n return f\"_{self.name}\"\n\n def __get__(self, obj, owner=None):\n if obj is None:\n return self\n try:\n return object.__getattribute__(obj, self.storage_name)\n except AttributeError as exc:\n raise FieldError(f\"{self.name} has no value\") from exc\n\n def __set__(self, obj, value) -> None:\n if not isinstance(value, int) or isinstance(value, bool):\n raise FieldError(f\"{self.name} must be an int, got {type(value).__name__}\")\n if not (self.lo <= value <= self.hi):\n raise FieldError(\n f\"{self.name}={value!r} outside [{self.lo}, {self.hi}]\"\n )\n object.__setattr__(obj, self.storage_name, value)\n"}, {"filename": "app/loader.py", "content": "\"\"\"Load settings from a JSON config file.\"\"\"\n\nfrom __future__ import annotations\n\nimport json\n\nfrom .fields import FieldError\nfrom .settings import SettingsBase\n\n\ndef load_settings(text: str) -> SettingsBase:\n \"\"\"Parse a JSON config text and build a SettingsBase from it.\"\"\"\n data = json.loads(text)\n if not isinstance(data, dict):\n raise FieldError(\"settings file must contain a JSON object\")\n coerced = {}\n for key, value in data.items():\n if isinstance(value, bool) or not isinstance(value, (int, str)):\n raise FieldError(f\"{key} must be an int, got {type(value).__name__}\")\n coerced[key] = int(value)\n return SettingsBase(**coerced)\n"}, {"filename": "app/settings.py", "content": "\"\"\"Application settings.\n\n`SettingsBase.__init__` accepts keyword overrides. For construction speed it\nvalidates the keyword names against the declared fields and then bulk-loads\nthe values into the instance dictionary, skipping per-field descriptor\noverhead on the hot path.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom .fields import FieldError, RangeField\n\nFIELD_NAMES = (\"port\", \"workers\", \"timeout_s\")\n\n\nclass SettingsBase:\n port = RangeField(1024, 65535)\n workers = RangeField(1, 64)\n timeout_s = RangeField(1, 3600)\n\n def __init__(self, **overrides) -> None:\n allowed = {\n name\n for name, value in type(self).__dict__.items()\n if isinstance(value, RangeField)\n }\n unknown = set(overrides) - allowed\n if unknown:\n raise FieldError(f\"unknown settings: {sorted(unknown)}\")\n # Fast path: bulk-load the values into the instance dict, skipping\n # per-field descriptor overhead.\n self.__dict__.update({f\"_{k}\": v for k, v in overrides.items()})\n\n def as_dict(self) -> dict:\n return {name: getattr(self, name) for name in FIELD_NAMES}\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport json\nimport os\nimport sys\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom app.fields import FieldError, RangeField\nfrom app.loader import load_settings\nfrom app.settings import SettingsBase\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\nVALID = {\"port\": 8080, \"workers\": 4, \"timeout_s\": 30}\n\n\ndef t_construction_validates():\n bad_configs = [\n {\"port\": 99999, \"workers\": 4, \"timeout_s\": 30},\n {\"port\": 80, \"workers\": 4, \"timeout_s\": 30},\n {\"port\": 1023, \"workers\": 4, \"timeout_s\": 30},\n {\"port\": 8080, \"workers\": 0, \"timeout_s\": 30},\n {\"port\": 8080, \"workers\": 65, \"timeout_s\": 30},\n {\"port\": 8080, \"workers\": 4, \"timeout_s\": 0},\n {\"port\": 8080, \"workers\": 4, \"timeout_s\": 3601},\n {\"port\": 8080, \"workers\": 4, \"timeout_s\": -1},\n ]\n for cfg in bad_configs:\n text = json.dumps(cfg)\n try:\n load_settings(text)\n except FieldError:\n continue\n raise AssertionError(f\"load_settings must reject {cfg}\")\n # constructor path as well\n try:\n SettingsBase(**cfg)\n except FieldError:\n continue\n raise AssertionError(f\"SettingsBase must reject {cfg}\")\n\n\ndef t_fast_path_enforces_types():\n # non-int values (strings from loosely typed config sources, floats,\n # booleans) must be rejected on construction exactly as on assignment\n for bad in [\"8080\", 8080.5, True, None, [1]]:\n try:\n SettingsBase(port=bad)\n except FieldError:\n continue\n raise AssertionError(f\"SettingsBase(port={bad!r}) must be rejected\")\n # a value that passes validation must round-trip identically through\n # both construction paths\n built = SettingsBase(**VALID)\n for key, value in VALID.items():\n assert getattr(built, key) == value, (key, getattr(built, key))\n\n\ndef t_valid_config_loads():\n s = load_settings(json.dumps(VALID))\n assert isinstance(s, SettingsBase)\n assert s.as_dict() == VALID, s.as_dict()\n # boundary values must be accepted\n edges = {\"port\": 1024, \"workers\": 1, \"timeout_s\": 1}\n s2 = load_settings(json.dumps(edges))\n assert s2.as_dict() == edges, s2.as_dict()\n edges2 = {\"port\": 65535, \"workers\": 64, \"timeout_s\": 3600}\n s3 = load_settings(json.dumps(edges2))\n assert s3.as_dict() == edges2, s3.as_dict()\n\n\ndef t_direct_assignment_validates():\n s = SettingsBase(**VALID)\n for key, bad_value in [\n (\"port\", 80), (\"workers\", 0), (\"timeout_s\", -5), (\"port\", 70000)\n ]:\n try:\n setattr(s, key, bad_value)\n except FieldError:\n continue\n raise AssertionError(f\"{key}={bad_value} must be rejected\")\n s.port = 9000\n assert s.port == 9000\n s.workers = 64\n assert s.workers == 64\n\n\ndef t_unknown_key_rejected():\n try:\n SettingsBase(nonsense=1)\n except FieldError:\n pass\n else:\n raise AssertionError(\"unknown settings must be rejected\")\n try:\n load_settings('{\"unknown\": 5}')\n except FieldError:\n pass\n else:\n raise AssertionError(\"load_settings must reject unknown keys\")\n\n\ndef t_field_metadata():\n port_field = SettingsBase.port\n assert isinstance(port_field, RangeField)\n assert port_field.name == \"port\", port_field.name\n assert port_field.lo == 1024 and port_field.hi == 65535\n w = SettingsBase.workers\n assert (w.lo, w.hi) == (1, 64)\n t = SettingsBase.timeout_s\n assert (t.lo, t.hi) == (1, 3600)\n\n\ndef main():\n check(\"settings::construction_validates\", t_construction_validates)\n check(\"settings::fast_path_enforces_types\", t_fast_path_enforces_types)\n check(\"settings::valid_config_loads\", t_valid_config_loads)\n check(\"settings::direct_assignment_validates\", t_direct_assignment_validates)\n check(\"settings::unknown_key_rejected\", t_unknown_key_rejected)\n check(\"fields::field_metadata\", t_field_metadata)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/app/settings.py\n+++ b/app/settings.py\n@@ -1,9 +1,11 @@\n \"\"\"Application settings.\n \n-`SettingsBase.__init__` accepts keyword overrides. For construction speed it\n-validates the keyword names against the declared fields and then bulk-loads\n-the values into the instance dictionary, skipping per-field descriptor\n-overhead on the hot path.\n+`SettingsBase.__init__` accepts keyword overrides. Overrides are applied\n+through the normal attribute protocol (`setattr`), so the `RangeField`\n+descriptors run their validation on the constructor path exactly as they do\n+on later assignments. The per-field cost is negligible compared to the JSON\n+parsing that precedes it, and skipping the descriptors silently disables\n+every declared constraint.\n \"\"\"\n \n from __future__ import annotations\n@@ -27,9 +29,9 @@\n unknown = set(overrides) - allowed\n if unknown:\n raise FieldError(f\"unknown settings: {sorted(unknown)}\")\n- # Fast path: bulk-load the values into the instance dict, skipping\n- # per-field descriptor overhead.\n- self.__dict__.update({f\"_{k}\": v for k, v in overrides.items()})\n+ # Apply through the attribute protocol so every field validates.\n+ for key, value in overrides.items():\n+ setattr(self, key, value)\n \n def as_dict(self) -> dict:\n return {name: getattr(self, name) for name in FIELD_NAMES}\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["settings::construction_validates", "settings::fast_path_enforces_types"], "pass_to_pass": ["settings::valid_config_loads", "settings::direct_assignment_validates", "settings::unknown_key_rejected", "fields::field_metadata"], "time_limit_s": 60, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "py-wal-crc", "title": "WAL checksum omits the record footer, so header corruption goes undetected", "language": "python", "category": "persistence-integrity", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# WAL recovery silently accepts corrupted record footers\n\n## Summary\n\nThe write-ahead log stores records in fixed-size slots. Each slot ends with a\nfooter (magic, version, sequence number, payload length, crc32). After a\nsimulated bit-flip in the footer of one record, recovery behaves in two\nbroken ways:\n\n1. A flipped sequence-number byte is returned as a valid record with a bogus\n sequence number; the index built from the log is silently poisoned.\n2. A flipped payload-length byte is not detected either: the decoder trusts\n the length field, so the record is read as the wrong bytes and recovery\n fails later with a confusing JSON error (or, for some values, silently\n drops the rest of the log).\n\nThe checksum is computed over the payload area only, so it cannot detect any\nfooter tampering. The checksum must authenticate the entire record: payload\narea plus footer, excluding the checksum field itself.\n\nRecovery rules (must hold exactly):\n\n- Any byte-level corruption anywhere in a record (payload OR footer fields:\n magic, version, sequence number, payload length, checksum) must raise\n `WalCorruptionError`.\n- A truncated final slot (the process died mid-append) must NOT raise:\n `read_all` returns all complete records before the torn slot.\n- Unused zero slots at the tail of the file are the end of the log, not\n corruption.\n\n## Environment\n\n- Python 3.11+, no third-party dependencies\n- Code layout: `store/` package (format, wal, index, recover)\n- Record limit: payloads up to 4075 bytes fit in one 4096-byte slot.\n\n## Reproduction\n\n```python\nimport tempfile, os\nfrom store.wal import WriteAheadLog\nfrom store.format import WalCorruptionError\n\npath = os.path.join(tempfile.mkdtemp(), \"wal.bin\")\nwal = WriteAheadLog(path)\nfor i in range(5):\n wal.append({\"key\": f\"k{i}\", \"value\": i})\n\nraw = bytearray(open(path, \"rb\").read())\n# record 3 lives at offset 2*4096; its footer starts at 4096*2 + 4075\nfoot = 2 * 4096 + 4075\nraw[foot + 5] ^= 0x80 # flip one bit of the sequence number\nopen(path, \"wb\").write(raw)\n\ntry:\n wal.read_all()\nexcept WalCorruptionError:\n print(\"detected\")\nelse:\n print(\"ACCEPTED - bug: footer corruption undetected\")\n```\n\n## Constraints\n\n- On-disk layout (4096-byte slots, footer with magic/version/seq/len/crc32)\n must stay unchanged.\n- `WriteAheadLog.append`, `.read_all`, `index.rebuild` public APIs stay\n stable.\n- Torn tail and unused zero tail must remain non-fatal.", "repo_files": [{"filename": "store/__init__.py", "content": "\"\"\"Append-only write-ahead log store.\"\"\"\n"}, {"filename": "store/format.py", "content": "\"\"\"Record framing for the write-ahead log.\n\nSlot layout (4096 bytes):\n\n [ payload area: 4075 bytes ][ footer: 21 bytes ]\n payload area = payload bytes, zero padded\n footer = struct \"<4sBQII\": magic(4) version(1) seq(8) len(4) crc(4)\n\nThe checksum protects the payload area. Zero-padded unused slots mark the\nend of the log; a file that ends mid-slot is a torn tail from a crash.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport struct\nimport zlib\n\nMAGIC = b\"WAL1\"\nVERSION = 1\n\nSLOT_SIZE = 4096\nFOOTER = struct.Struct(\"<4sBQII\")\nFOOTER_SIZE = FOOTER.size # 21\nPAYLOAD_AREA = SLOT_SIZE - FOOTER_SIZE # 4075\nMAX_PAYLOAD = PAYLOAD_AREA\n\n\nclass WalError(Exception):\n \"\"\"Base class for write-ahead log errors.\"\"\"\n\n\nclass WalCorruptionError(WalError):\n \"\"\"A record failed its integrity checks.\"\"\"\n\n\nclass WalTornTailError(WalError):\n \"\"\"The log ends with an incomplete slot (crash during append).\"\"\"\n\n\ndef encode(seq: int, payload: bytes) -> bytes:\n \"\"\"Serialize one record into a full slot.\"\"\"\n if len(payload) > MAX_PAYLOAD:\n raise WalCorruptionError(\n f\"payload of {len(payload)} bytes exceeds the {MAX_PAYLOAD} byte limit\"\n )\n area = payload + b\"\\x00\" * (PAYLOAD_AREA - len(payload))\n # The checksum protects the payload area.\n crc = zlib.crc32(area) & 0xFFFFFFFF\n footer = FOOTER.pack(MAGIC, VERSION, seq, len(payload), crc)\n return area + footer\n\n\ndef decode(slot: bytes):\n \"\"\"Decode one full slot. Returns (seq, payload).\n\n Raises WalCorruptionError for bad magic, bad version or bad checksum.\n \"\"\"\n if len(slot) != SLOT_SIZE:\n raise WalTornTailError(\"incomplete slot\")\n area = slot[:PAYLOAD_AREA]\n magic, version, seq, payload_len, crc = FOOTER.unpack_from(slot, PAYLOAD_AREA)\n if magic != MAGIC:\n raise WalCorruptionError(\"bad magic in record footer\")\n if version != VERSION:\n raise WalCorruptionError(f\"unsupported record version {version}\")\n if zlib.crc32(area) & 0xFFFFFFFF != crc:\n raise WalCorruptionError(\"checksum mismatch\")\n return seq, area[:payload_len]\n"}, {"filename": "store/index.py", "content": "\"\"\"Secondary index rebuilt from the log: latest sequence wins.\"\"\"\n\nfrom __future__ import annotations\n\n\ndef rebuild(wal) -> dict:\n \"\"\"Return {key: {\"value\": ..., \"seq\": ...}} with the latest seq per key.\"\"\"\n index: dict = {}\n for seq, record in wal.read_all():\n key = record[\"key\"]\n current = index.get(key)\n if current is None or seq > current[\"seq\"]:\n index[key] = {\"value\": record[\"value\"], \"seq\": seq}\n return index\n"}, {"filename": "store/recover.py", "content": "\"\"\"Recovery entry point: rebuild the index from a log file.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .index import rebuild\nfrom .wal import WriteAheadLog\n\n\ndef recover(path: str) -> dict:\n \"\"\"Open the log at path and rebuild the in-memory index.\"\"\"\n return rebuild(WriteAheadLog(path))\n"}, {"filename": "store/wal.py", "content": "\"\"\"Write-ahead log: append records, scan them back.\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\n\nfrom .format import (\n SLOT_SIZE,\n decode,\n encode,\n)\n\n\nclass WriteAheadLog:\n def __init__(self, path: str) -> None:\n self.path = path\n parent = os.path.dirname(os.path.abspath(path))\n if parent:\n os.makedirs(parent, exist_ok=True)\n\n def append(self, record: dict) -> int:\n \"\"\"Append one JSON record; returns its sequence number (1-based).\"\"\"\n records, _end = self._scan()\n seq = (records[-1][0] + 1) if records else 1\n payload = json.dumps(record, sort_keys=True, separators=(\",\", \":\")).encode()\n with open(self.path, \"ab\") as handle:\n handle.write(encode(seq, payload))\n handle.flush()\n os.fsync(handle.fileno())\n return seq\n\n def read_all(self) -> list[tuple[int, dict]]:\n \"\"\"Return every complete record. A torn tail stops the scan quietly.\"\"\"\n records, _end = self._scan()\n return [(seq, json.loads(payload)) for seq, payload in records]\n\n def _scan(self):\n \"\"\"Scan the file, tolerating a torn tail and unused zero slots.\"\"\"\n if not os.path.exists(self.path):\n return [], 0\n with open(self.path, \"rb\") as handle:\n data = handle.read()\n records = []\n offset = 0\n while offset < len(data):\n if offset + SLOT_SIZE > len(data):\n break # torn tail: crash during append\n slot = data[offset : offset + SLOT_SIZE]\n if slot == b\"\\x00\" * SLOT_SIZE:\n break # unused tail\n seq, payload = decode(slot)\n records.append((seq, payload))\n offset += SLOT_SIZE\n return records, offset\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport os\nimport sys\nimport tempfile\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.dirname(HERE))\n\nfrom store.format import (\n PAYLOAD_AREA,\n SLOT_SIZE,\n WalCorruptionError,\n encode,\n)\nfrom store.wal import WriteAheadLog\nfrom store.index import rebuild\nfrom store.recover import recover\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\ndef make_log(tmp, n=5):\n wal = WriteAheadLog(os.path.join(tmp, \"wal.bin\"))\n for i in range(n):\n wal.append({\"key\": f\"k{i}\", \"value\": i})\n return wal\n\n\ndef raw_bytes(wal):\n with open(wal.path, \"rb\") as handle:\n return bytearray(handle.read())\n\n\ndef write_raw(wal, raw):\n with open(wal.path, \"wb\") as handle:\n handle.write(bytes(raw))\n\n\ndef footer_offset(slot_index):\n return slot_index * SLOT_SIZE + PAYLOAD_AREA\n\n\ndef t_seq_field_corruption_detected():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp)\n raw = raw_bytes(wal)\n foot = footer_offset(2) # record 3\n raw[foot + 5] ^= 0x80 # flip one bit of the sequence number\n write_raw(wal, raw)\n try:\n wal.read_all()\n except WalCorruptionError:\n return\n raise AssertionError(\"footer sequence-number corruption must be detected\")\n\n\ndef t_length_field_corruption_detected():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp)\n raw = raw_bytes(wal)\n foot = footer_offset(2) # record 3\n raw[foot + 16] ^= 0x01 # flip a bit of the payload length\n write_raw(wal, raw)\n try:\n wal.read_all()\n except WalCorruptionError:\n return\n raise AssertionError(\"footer payload-length corruption must be detected\")\n\n\ndef t_clean_roundtrip():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp, 10)\n records = wal.read_all()\n assert len(records) == 10, len(records)\n for i, (seq, record) in enumerate(records, start=1):\n assert seq == i, (i, seq)\n assert record == {\"key\": f\"k{i - 1}\", \"value\": i - 1}, record\n\n\ndef t_torn_tail_returns_prior_records():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp, 5)\n raw = raw_bytes(wal)\n # crash mid-append of the 6th slot: keep 4 slots and half of the 5th\n torn = raw[: 4 * SLOT_SIZE + 1000]\n write_raw(wal, torn)\n records = wal.read_all()\n assert len(records) == 4, f\"expected 4 records before the torn slot, got {len(records)}\"\n assert [s for s, _ in records] == [1, 2, 3, 4]\n\n\ndef t_bad_magic_detected():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp)\n raw = raw_bytes(wal)\n raw[footer_offset(1)] = ord(\"X\")\n write_raw(wal, raw)\n try:\n wal.read_all()\n except WalCorruptionError:\n return\n raise AssertionError(\"bad magic must be detected\")\n\n\ndef t_bad_checksum_detected():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp)\n raw = raw_bytes(wal)\n raw[10] ^= 0xFF # payload byte of the first record\n write_raw(wal, raw)\n try:\n wal.read_all()\n except WalCorruptionError:\n return\n raise AssertionError(\"payload corruption must be detected by the checksum\")\n\n\ndef t_bad_version_detected():\n with tempfile.TemporaryDirectory() as tmp:\n wal = make_log(tmp)\n raw = raw_bytes(wal)\n raw[footer_offset(0) + 4] = 9 # version byte in the footer\n write_raw(wal, raw)\n try:\n wal.read_all()\n except WalCorruptionError:\n return\n raise AssertionError(\"bad version must be detected\")\n\n\ndef t_large_payload_roundtrip():\n with tempfile.TemporaryDirectory() as tmp:\n wal = WriteAheadLog(os.path.join(tmp, \"wal.bin\"))\n big = \"x\" * 4000\n wal.append({\"key\": \"big\", \"value\": big})\n wal.append({\"key\": \"small\", \"value\": 1})\n records = wal.read_all()\n assert len(records) == 2, len(records)\n assert records[0][1][\"value\"] == big\n assert records[1][1] == {\"key\": \"small\", \"value\": 1}\n\n\ndef t_rebuild_latest_seq_wins():\n with tempfile.TemporaryDirectory() as tmp:\n wal = WriteAheadLog(os.path.join(tmp, \"wal.bin\"))\n wal.append({\"key\": \"a\", \"value\": 1})\n wal.append({\"key\": \"b\", \"value\": 2})\n wal.append({\"key\": \"a\", \"value\": 3})\n wal.append({\"key\": \"a\", \"value\": 99})\n index = rebuild(wal)\n assert index[\"a\"] == {\"value\": 99, \"seq\": 4}, index\n assert index[\"b\"] == {\"value\": 2, \"seq\": 2}, index\n # recovery entry point must produce the same index\n assert recover(wal.path) == index\n\n\ndef main():\n check(\"wal::seq_field_corruption_detected\", t_seq_field_corruption_detected)\n check(\"wal::length_field_corruption_detected\", t_length_field_corruption_detected)\n check(\"wal::clean_roundtrip\", t_clean_roundtrip)\n check(\"wal::torn_tail_returns_prior_records\", t_torn_tail_returns_prior_records)\n check(\"wal::bad_magic_detected\", t_bad_magic_detected)\n check(\"wal::bad_checksum_detected\", t_bad_checksum_detected)\n check(\"wal::bad_version_detected\", t_bad_version_detected)\n check(\"wal::large_payload_roundtrip\", t_large_payload_roundtrip)\n check(\"index::rebuild_latest_seq_wins\", t_rebuild_latest_seq_wins)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/store/format.py\n+++ b/store/format.py\n@@ -6,8 +6,12 @@\n payload area = payload bytes, zero padded\n footer = struct \"<4sBQII\": magic(4) version(1) seq(8) len(4) crc(4)\n \n-The checksum protects the payload area. Zero-padded unused slots mark the\n-end of the log; a file that ends mid-slot is a torn tail from a crash.\n+The checksum authenticates the ENTIRE record: the payload area plus every\n+footer field except the checksum field itself. Without that, a bit flip in\n+the sequence number or the payload length passes unnoticed and recovery\n+silently returns corrupted records (or fails later with a confusing JSON\n+error). Zero-padded unused slots mark the end of the log; a file that ends\n+mid-slot is a torn tail from a crash.\n \"\"\"\n \n from __future__ import annotations\n@@ -23,6 +27,8 @@\n FOOTER_SIZE = FOOTER.size # 21\n PAYLOAD_AREA = SLOT_SIZE - FOOTER_SIZE # 4075\n MAX_PAYLOAD = PAYLOAD_AREA\n+# The checksum covers everything except its own 4 bytes at the very end.\n+CRC_COVERAGE = SLOT_SIZE - 4\n \n \n class WalError(Exception):\n@@ -44,8 +50,8 @@\n f\"payload of {len(payload)} bytes exceeds the {MAX_PAYLOAD} byte limit\"\n )\n area = payload + b\"\\x00\" * (PAYLOAD_AREA - len(payload))\n- # The checksum protects the payload area.\n- crc = zlib.crc32(area) & 0xFFFFFFFF\n+ footer_wo_crc = FOOTER.pack(MAGIC, VERSION, seq, len(payload), 0)[:17]\n+ crc = zlib.crc32(area + footer_wo_crc) & 0xFFFFFFFF\n footer = FOOTER.pack(MAGIC, VERSION, seq, len(payload), crc)\n return area + footer\n \n@@ -53,16 +59,22 @@\n def decode(slot: bytes):\n \"\"\"Decode one full slot. Returns (seq, payload).\n \n- Raises WalCorruptionError for bad magic, bad version or bad checksum.\n+ Raises WalCorruptionError for bad magic, bad version, oversized payload\n+ length or checksum mismatch; the checksum covers payload and footer\n+ fields, so any single-bit corruption in the record is caught.\n \"\"\"\n if len(slot) != SLOT_SIZE:\n raise WalTornTailError(\"incomplete slot\")\n- area = slot[:PAYLOAD_AREA]\n magic, version, seq, payload_len, crc = FOOTER.unpack_from(slot, PAYLOAD_AREA)\n if magic != MAGIC:\n raise WalCorruptionError(\"bad magic in record footer\")\n if version != VERSION:\n raise WalCorruptionError(f\"unsupported record version {version}\")\n- if zlib.crc32(area) & 0xFFFFFFFF != crc:\n+ if payload_len > MAX_PAYLOAD:\n+ raise WalCorruptionError(\n+ f\"payload length {payload_len} exceeds the {MAX_PAYLOAD} byte limit\"\n+ )\n+ covered = slot[:CRC_COVERAGE]\n+ if zlib.crc32(covered) & 0xFFFFFFFF != crc:\n raise WalCorruptionError(\"checksum mismatch\")\n- return seq, area[:payload_len]\n+ return seq, slot[:payload_len]\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["wal::seq_field_corruption_detected", "wal::length_field_corruption_detected"], "pass_to_pass": ["wal::clean_roundtrip", "wal::torn_tail_returns_prior_records", "wal::bad_magic_detected", "wal::bad_checksum_detected", "wal::bad_version_detected", "wal::large_payload_roundtrip", "index::rebuild_latest_seq_wins"], "time_limit_s": 60, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "sql-notin-cycle", "title": "NOT IN with NULL silently drops all rows; recursive CTE loops forever on cyclic data", "language": "sql", "category": "sql-semantics", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Employee report excludes everyone; department tree query never terminates\n\n## Summary\n\nTwo defects in the reporting SQL library (SQLite):\n\n1. `active_employees_not_in(conn, excluded)` returns ZERO rows whenever the\n exclusion list contains a NULL. SQL three-valued logic: comparing against\n a NULL yields UNKNOWN, and `NOT IN` over a list containing any NULL can\n never be TRUE, so the whole predicate filters out every row. Production\n callers build the exclusion list from a table that contains NULLs, so the\n report comes back empty and nobody notices.\n\n2. `dept_tree(conn, root_id)` walks the org hierarchy with a recursive CTE\n that has no cycle guard. Departments SRE (id 5) and Ops (id 6) list each\n other as parent, so a query rooted anywhere in that cycle never\n terminates.\n\n## Environment\n\n- Python 3.11+, sqlite3 from the standard library\n- Code layout: `queries/` package (seed, reports, hierarchy, run_report)\n\n## Reproduction\n\n```python\nimport sqlite3\nfrom queries.seed import seed\nfrom queries.reports import active_employees_not_in\nfrom queries.hierarchy import dept_tree\n\nconn = sqlite3.connect(\":memory:\")\nseed(conn)\nprint(active_employees_not_in(conn, [3, None])) # [] -> BUG: must return the rows\n\nconn.set_progress_handler(lambda: 0, 1) # will also stop the hung query below\ntry:\n dept_tree(conn, 5) # never returns -> BUG\nexcept Exception as exc:\n print(type(exc).__name__)\n```\n\n## Specification (must hold exactly)\n\n- `NOT IN` semantics with NULL exclusion values: the NULL entries must be\n ignored, not poison the predicate. `active_employees_not_in(conn, [3, None])`\n must return exactly the active employees outside department 3.\n- An empty exclusion list must return all active employees.\n- `dept_tree(conn, root_id)` must terminate on cyclic data and return each\n reachable department exactly once with its minimum depth, ordered by\n (depth, id). The recursive CTE must not rely on a global depth limit that\n silently truncates legitimate trees.", "repo_files": [{"filename": "queries/__init__.py", "content": "\"\"\"Reporting SQL library.\"\"\"\n"}, {"filename": "queries/hierarchy.py", "content": "\"\"\"Department hierarchy queries.\"\"\"\n\nfrom __future__ import annotations\n\nimport sqlite3\n\n\ndef dept_tree(conn: sqlite3.Connection, root_id: int):\n \"\"\"Return (id, name, depth) for every department reachable from root.\"\"\"\n sql = \"\"\"\n WITH RECURSIVE tree AS (\n SELECT id, name, parent_id, 0 AS depth\n FROM departments\n WHERE id = ?\n UNION ALL\n SELECT d.id, d.name, d.parent_id, tree.depth + 1\n FROM departments d\n JOIN tree ON d.parent_id = tree.id\n )\n SELECT id, name, depth FROM tree ORDER BY depth, id\n \"\"\"\n return conn.execute(sql, (root_id,)).fetchall()\n"}, {"filename": "queries/reports.py", "content": "\"\"\"Employee reports.\"\"\"\n\nfrom __future__ import annotations\n\nimport sqlite3\n\n\ndef active_employees_not_in(conn: sqlite3.Connection, excluded):\n \"\"\"Active employees whose department is not in the exclusion list.\"\"\"\n excluded = list(excluded)\n if not excluded:\n return conn.execute(\n \"SELECT id, name, dept_id FROM employees WHERE active = 1 ORDER BY id\"\n ).fetchall()\n placeholders = \",\".join(\"?\" for _ in excluded)\n sql = (\n \"SELECT id, name, dept_id FROM employees \"\n f\"WHERE active = 1 AND dept_id NOT IN ({placeholders}) ORDER BY id\"\n )\n return conn.execute(sql, excluded).fetchall()\n\n\ndef active_employees(conn: sqlite3.Connection):\n return conn.execute(\n \"SELECT id, name, dept_id FROM employees WHERE active = 1 ORDER BY id\"\n ).fetchall()\n"}, {"filename": "queries/run_report.py", "content": "\"\"\"CLI: print a report.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport sqlite3\n\nfrom .hierarchy import dept_tree\nfrom .reports import active_employees_not_in\nfrom .seed import seed\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--exclude\", type=int, nargs=\"*\", default=[])\n parser.add_argument(\"--root\", type=int, default=1)\n args = parser.parse_args()\n\n conn = sqlite3.connect(\":memory:\")\n seed(conn)\n print(\"employees:\", active_employees_not_in(conn, args.exclude))\n print(\"tree:\", dept_tree(conn, args.root))\n\n\nif __name__ == \"__main__\":\n main()\n"}, {"filename": "queries/seed.py", "content": "\"\"\"Database schema and seed data.\"\"\"\n\nfrom __future__ import annotations\n\nimport sqlite3\n\nSCHEMA = \"\"\"\nCREATE TABLE departments (\n id INTEGER PRIMARY KEY,\n name TEXT NOT NULL,\n parent_id INTEGER REFERENCES departments(id)\n);\n\nCREATE TABLE employees (\n id INTEGER PRIMARY KEY,\n name TEXT NOT NULL,\n dept_id INTEGER REFERENCES departments(id),\n active INTEGER NOT NULL DEFAULT 1\n);\n\"\"\"\n\nDEPARTMENTS = [\n # (id, name, parent_id) -- SRE (5) and Ops (6) form a cycle:\n # SRE's parent is Ops, Ops's parent is SRE.\n (1, \"HQ\", None),\n (2, \"Engineering\", 1),\n (3, \"Sales\", 1),\n (4, \"Platform\", 2),\n (5, \"SRE\", 6),\n (6, \"Ops\", 5),\n (7, \"Research\", 6),\n]\n\nEMPLOYEES = [\n # (id, name, dept_id, active)\n (1, \"Ada\", 2, 1),\n (2, \"Bruno\", 2, 0),\n (3, \"Clara\", 3, 1),\n (4, \"Devi\", 4, 1),\n (5, \"Eli\", None, 1), # no department\n (6, \"Farah\", 3, 0),\n (7, \"Gustav\", 5, 1),\n (8, \"Hana\", 7, 1),\n]\n\n\ndef seed(conn: sqlite3.Connection) -> None:\n conn.executescript(SCHEMA)\n conn.executemany(\n \"INSERT INTO departments (id, name, parent_id) VALUES (?, ?, ?)\",\n DEPARTMENTS,\n )\n conn.executemany(\n \"INSERT INTO employees (id, name, dept_id, active) VALUES (?, ?, ?, ?)\",\n EMPLOYEES,\n )\n conn.commit()\n"}], "test_files": [{"filename": "run_tests.py", "content": "\"\"\"Hidden verification suite. Emits TAP lines; exit 1 if any test fails.\"\"\"\n\nimport os\nimport sqlite3\nimport sys\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.dirname(HERE))\n\nfrom queries.hierarchy import dept_tree\nfrom queries.reports import active_employees_not_in, active_employees\nfrom queries.seed import seed\n\n_TAP = []\n\n\ndef check(name, fn):\n try:\n fn()\n _TAP.append((True, name, \"\"))\n except Exception as exc: # noqa: BLE001\n _TAP.append((False, name, f\"{type(exc).__name__}: {exc}\"))\n\n\ndef fresh_db():\n conn = sqlite3.connect(\":memory:\")\n seed(conn)\n return conn\n\n\ndef guard(conn, max_calls=300):\n \"\"\"Abort runaway queries (cycle protection check).\n\n The progress handler runs every 1000 VM steps. Legitimate queries on the\n seeded data finish in far fewer than 1000 steps; an unguarded recursive\n CTE on the cyclic data never stops, so it trips the budget.\n \"\"\"\n state = {\"calls\": 0}\n\n def handler():\n state[\"calls\"] += 1\n return 1 if state[\"calls\"] > max_calls else 0\n\n conn.set_progress_handler(handler, 1000)\n\n\nACTIVE_IDS = {1, 3, 4, 5, 7, 8}\n\n\ndef t_not_in_with_null_returns_rows():\n conn = fresh_db()\n rows = active_employees_not_in(conn, [3, None])\n ids = {r[0] for r in rows}\n expected = ACTIVE_IDS - {3} # dept 3 excluded, no NULL dept in active set\n assert ids == expected, f\"got {sorted(ids)}, want {sorted(expected)}\"\n # a list of only NULLs must behave like an empty exclusion list\n rows_all = active_employees_not_in(conn, [None, None])\n assert {r[0] for r in rows_all} == ACTIVE_IDS, rows_all\n\n\ndef t_not_in_empty_list():\n conn = fresh_db()\n rows = active_employees_not_in(conn, [])\n assert {r[0] for r in rows} == ACTIVE_IDS, rows\n\n\ndef t_cycle_safe_terminates():\n # root 5 sits inside the 5 <-> 6 cycle; the unguarded CTE never terminates\n conn = fresh_db()\n guard(conn)\n try:\n rows = dept_tree(conn, 5)\n except sqlite3.OperationalError as exc:\n raise AssertionError(f\"dept_tree did not terminate: {exc}\")\n got = [(r[0], r[1], r[2]) for r in rows]\n expected = [\n (5, \"SRE\", 0),\n (6, \"Ops\", 1),\n (7, \"Research\", 2),\n ]\n assert got == expected, f\"got {got}, want {expected}\"\n # each reachable department exactly once\n ids = [r[0] for r in got]\n assert len(ids) == len(set(ids)), f\"duplicate departments: {ids}\"\n\n\ndef t_basic_exclusion():\n conn = fresh_db()\n rows = active_employees_not_in(conn, [2])\n assert {r[0] for r in rows} == ACTIVE_IDS - {1}, rows\n\n\ndef t_inactive_filtered():\n conn = fresh_db()\n rows = active_employees_not_in(conn, [])\n assert 2 not in {r[0] for r in rows} and 6 not in {r[0] for r in rows}\n assert {r[0] for r in rows} == ACTIVE_IDS\n\n\ndef t_tree_depth_simple():\n conn = fresh_db()\n rows = dept_tree(conn, 1)\n got = [(r[0], r[1], r[2]) for r in rows]\n expected = [\n (1, \"HQ\", 0),\n (2, \"Engineering\", 1),\n (3, \"Sales\", 1),\n (4, \"Platform\", 2),\n ]\n assert got == expected, f\"got {got}, want {expected}\"\n\n\ndef t_row_order_and_uniqueness():\n conn = fresh_db()\n guard(conn)\n rows = dept_tree(conn, 1)\n depths = [r[2] for r in rows]\n assert depths == sorted(depths), f\"rows must be ordered by depth: {depths}\"\n ids = [r[0] for r in rows]\n assert len(ids) == len(set(ids)), \"duplicate rows\"\n\n\ndef main():\n check(\"reports::not_in_with_null_returns_rows\", t_not_in_with_null_returns_rows)\n check(\"reports::not_in_empty_list\", t_not_in_empty_list)\n check(\"hierarchy::cycle_safe_terminates\", t_cycle_safe_terminates)\n check(\"reports::basic_exclusion\", t_basic_exclusion)\n check(\"reports::inactive_filtered\", t_inactive_filtered)\n check(\"hierarchy::tree_depth_simple\", t_tree_depth_simple)\n check(\"hierarchy::row_order_and_uniqueness\", t_row_order_and_uniqueness)\n failed = 0\n for i, (ok, name, diag) in enumerate(_TAP, 1):\n if ok:\n print(f\"ok {i} - {name}\")\n else:\n failed += 1\n print(f\"not ok {i} - {name}\")\n print(f\" # {diag}\")\n return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"}], "gold_patch": "--- a/queries/hierarchy.py\n+++ b/queries/hierarchy.py\n@@ -6,17 +6,31 @@\n \n \n def dept_tree(conn: sqlite3.Connection, root_id: int):\n- \"\"\"Return (id, name, depth) for every department reachable from root.\"\"\"\n+ \"\"\"Return (id, name, depth) for every department reachable from root.\n+\n+ Cycle-safe. Every row carries the path of department ids used to\n+ reach it, and a department already on that path is not expanded\n+ again, so cyclic parent links (for example SRE and Ops listing each\n+ other as parent) terminate instead of looping forever. A department\n+ reachable through several simple paths (a diamond) is reported once,\n+ at its minimum depth, because the final SELECT groups by id and\n+ takes MIN(depth). No global depth limit is applied, so legitimately\n+ deep trees are never silently truncated.\n+ \"\"\"\n sql = \"\"\"\n- WITH RECURSIVE tree AS (\n- SELECT id, name, parent_id, 0 AS depth\n+ WITH RECURSIVE walk(id, name, depth, path) AS (\n+ SELECT id, name, 0, '/' || id || '/'\n FROM departments\n WHERE id = ?\n UNION ALL\n- SELECT d.id, d.name, d.parent_id, tree.depth + 1\n+ SELECT d.id, d.name, walk.depth + 1, walk.path || d.id || '/'\n FROM departments d\n- JOIN tree ON d.parent_id = tree.id\n+ JOIN walk ON d.parent_id = walk.id\n+ WHERE walk.path NOT LIKE '%/' || d.id || '/%'\n )\n- SELECT id, name, depth FROM tree ORDER BY depth, id\n+ SELECT id, name, MIN(depth) AS depth\n+ FROM walk\n+ GROUP BY id\n+ ORDER BY depth, id\n \"\"\"\n return conn.execute(sql, (root_id,)).fetchall()\n--- a/queries/reports.py\n+++ b/queries/reports.py\n@@ -4,23 +4,31 @@\n \n import sqlite3\n \n+_ACTIVE_SQL = \"SELECT id, name, dept_id FROM employees WHERE active = 1\"\n+\n \n def active_employees_not_in(conn: sqlite3.Connection, excluded):\n- \"\"\"Active employees whose department is not in the exclusion list.\"\"\"\n- excluded = list(excluded)\n+ \"\"\"Active employees whose department is not in the exclusion list.\n+\n+ NULLs in ``excluded`` are ignored. Under SQL three-valued logic a\n+ ``NOT IN`` list containing even one NULL evaluates to UNKNOWN for\n+ every candidate row, which silently empties the report, so the NULL\n+ entries are dropped here and the comparison runs as ``NOT EXISTS``.\n+ NOT EXISTS also keeps employees with no department (their dept_id\n+ never matches a concrete value), and it is immune to the same\n+ poisoning regardless of which side is NULL.\n+ \"\"\"\n+ excluded = [e for e in excluded if e is not None]\n if not excluded:\n- return conn.execute(\n- \"SELECT id, name, dept_id FROM employees WHERE active = 1 ORDER BY id\"\n- ).fetchall()\n- placeholders = \",\".join(\"?\" for _ in excluded)\n+ return conn.execute(f\"{_ACTIVE_SQL} ORDER BY id\").fetchall()\n+ values = \" UNION ALL \".join([\"SELECT ? AS dept\"] * len(excluded))\n sql = (\n- \"SELECT id, name, dept_id FROM employees \"\n- f\"WHERE active = 1 AND dept_id NOT IN ({placeholders}) ORDER BY id\"\n+ f\"{_ACTIVE_SQL} AND NOT EXISTS (\"\n+ f\"SELECT 1 FROM ({values}) AS excluded_dept \"\n+ f\"WHERE excluded_dept.dept = employees.dept_id) ORDER BY id\"\n )\n return conn.execute(sql, excluded).fetchall()\n \n \n def active_employees(conn: sqlite3.Connection):\n- return conn.execute(\n- \"SELECT id, name, dept_id FROM employees WHERE active = 1 ORDER BY id\"\n- ).fetchall()\n+ return conn.execute(f\"{_ACTIVE_SQL} ORDER BY id\").fetchall()\n", "test_command": ["python3", "tests/run_tests.py"], "fail_to_pass": ["reports::not_in_with_null_returns_rows", "reports::basic_exclusion", "hierarchy::cycle_safe_terminates"], "pass_to_pass": ["reports::not_in_empty_list", "reports::inactive_filtered", "hierarchy::tree_depth_simple", "hierarchy::row_order_and_uniqueness"], "time_limit_s": 60, "sandbox_image": "python:3.12-slim", "sandbox_system_deps": []} {"task_id": "ts-prototype-pollution", "title": "Config deep merge pollutes Object.prototype via __proto__ keys", "language": "typescript", "category": "type-soundness", "difficulty": "expert", "source": "original-synthetic", "license": "MIT", "created": "2026-10-13", "prompt": "# Config merge pollutes Object.prototype and mutates defaults\n\n## Summary\n\nOur configuration loader merges a JSON override document onto a defaults\nobject. Security review found that an override document containing the JSON\nkey `\"__proto__\"` pollutes `Object.prototype` globally: after loading such a\nconfig, EVERY object in the process sees the injected property. A nested\n`\"__proto__\"` key (one level deeper) does the same. Additionally, the merge\nmutates the defaults object in place, so a config loaded once changes what\nlater loads see.\n\nThe merge walks source keys with the `in` operator, which is true for\ninherited properties. For the key `__proto__`, `key in target` is true and\n`target[key]` resolves the prototype accessor to `Object.prototype`, so the\nrecursive merge writes attacker-controlled properties onto the global\nprototype.\n\n## Specification (must hold exactly)\n\n- Keys coming from a JSON document are DATA keys: they must be applied as\n own properties and never written through inherited accessors.\n- Merging must never modify `Object.prototype` (or any object's prototype):\n after any merge, `({} as Record).polluted === undefined`\n and `Object.getPrototypeOf(result) === Object.prototype`.\n- The merge must not mutate its inputs: loading a config must not change the\n defaults object.\n- `__proto__`, `constructor` and `prototype` keys from the source become\n inert own data properties (they must not alter behavior of the result's\n prototype chain).\n\n## Environment\n\n- Node.js 22+ with built-in TypeScript type stripping (`node file.ts`)\n- Code layout: `src/` (types, merge, config, cli)\n\n## Reproduction\n\n```ts\nimport { deepMerge } from \"./src/merge.js\";\n\ndeepMerge({}, JSON.parse('{\"__proto__\": {\"polluted\": true}}'));\nconsole.log(({} as Record).polluted); // true -> BUG\n```\n\n## Constraints\n\n- `deepMerge(target, source)` and `loadConfig(text)` signatures stay stable.\n- Normal merge semantics (nested object merge, arrays replaced, primitives\n override, three-level nesting) must be preserved.", "repo_files": [{"filename": "package.json", "content": "{\n \"name\": \"config-loader\",\n \"version\": \"1.0.0\",\n \"type\": \"module\",\n \"private\": true\n}\n"}, {"filename": "src/cli.ts", "content": "/** Command line entry point: load a config file and print it. */\n\nimport { readFileSync } from \"node:fs\";\n\nimport { loadConfig } from \"./config.ts\";\n\nconst path = process.argv[2];\nif (!path) {\n console.error(\"usage: config \");\n process.exit(2);\n}\nconst text = readFileSync(path, \"utf8\");\nconsole.log(JSON.stringify(loadConfig(text), null, 2));\n"}, {"filename": "src/config.ts", "content": "/** Configuration loading. */\n\nimport type { JsonObject } from \"./types.ts\";\nimport { deepMerge } from \"./merge.ts\";\n\nexport const DEFAULTS: JsonObject = {\n server: { host: \"127.0.0.1\", port: 8080 },\n logging: { level: \"info\", format: \"json\" },\n features: { newDashboard: false, betaApi: false },\n};\n\nexport function loadConfig(text: string): JsonObject {\n const overrides = JSON.parse(text) as JsonObject;\n return deepMerge(DEFAULTS, overrides);\n}\n"}, {"filename": "src/merge.ts", "content": "/** Deep merge for configuration documents. */\n\nimport type { Json, JsonObject } from \"./types.ts\";\nimport { isJsonObject } from \"./types.ts\";\n\nexport function deepMerge(\n target: JsonObject,\n source: JsonObject,\n): JsonObject {\n for (const key of Object.keys(source)) {\n const incoming = source[key];\n if (isJsonObject(incoming)) {\n if (!(key in target) || !isJsonObject(target[key])) {\n target[key] = {};\n }\n deepMerge(target[key] as JsonObject, incoming);\n } else {\n target[key] = incoming;\n }\n }\n return target;\n}\n"}, {"filename": "src/types.ts", "content": "/** JSON value model. */\n\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [key: string]: Json };\n\nexport type JsonObject = { [key: string]: Json };\n\nexport function isJsonObject(value: Json): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"}], "test_files": [{"filename": "run_tests.ts", "content": "/** Hidden verification suite (TAP output). */\n\nimport { deepMerge } from \"../src/merge.ts\";\nimport { DEFAULTS, loadConfig } from \"../src/config.ts\";\nimport { assert, check, deepEqual, report } from \"./tap.ts\";\n\nfunction asRecord(value: unknown): Record {\n return value as Record;\n}\n\nfunction t_proto_key_does_not_pollute() {\n deepMerge({}, JSON.parse('{\"__proto__\": {\"polluted\": true}}'));\n const probe = asRecord({}).polluted;\n assert(\n probe === undefined,\n `Object.prototype was polluted: polluted=${String(probe)}`,\n );\n}\n\nfunction t_nested_proto_key_does_not_pollute() {\n deepMerge({ a: {} }, JSON.parse('{\"a\": {\"__proto__\": {\"evil\": 1}}}'));\n const probe = asRecord({}).evil;\n assert(probe === undefined, `nested __proto__ polluted the prototype: evil=${String(probe)}`);\n const target = { a: {} };\n deepMerge(target, JSON.parse('{\"a\": {\"__proto__\": {\"evil\": 1}}}'));\n const probe2 = asRecord({}).evil;\n assert(probe2 === undefined, `nested __proto__ polluted the prototype (2): evil=${String(probe2)}`);\n}\n\nfunction t_result_prototype_intact() {\n const result = deepMerge({}, JSON.parse('{\"__proto__\": {\"x\": 1}}'));\n assert(\n Object.getPrototypeOf(result) === Object.prototype,\n \"result prototype was replaced\",\n );\n assert(asRecord(result).x === undefined, \"result must not inherit x from a replaced prototype\");\n}\n\nfunction t_defaults_not_mutated_across_loads() {\n const first = loadConfig('{\"server\": {\"port\": 9099}}');\n deepEqual(first.server, { host: \"127.0.0.1\", port: 9099 }, \"first load\");\n const second = loadConfig(\"{}\");\n deepEqual(second, DEFAULTS, \"second load must see pristine defaults\");\n deepEqual(\n DEFAULTS.server as unknown as Record,\n { host: \"127.0.0.1\", port: 8080 },\n \"defaults must not be mutated\",\n );\n}\n\nfunction t_basic_nested_merge() {\n const result = deepMerge({ a: { b: 1 }, keep: \"yes\" }, { a: { c: 2 } });\n deepEqual(result, { a: { b: 1, c: 2 }, keep: \"yes\" }, \"basic nested merge\");\n}\n\nfunction t_arrays_replaced() {\n const result = deepMerge({ list: [1, 2, 3] }, { list: [9] });\n deepEqual(result, { list: [9] }, \"arrays must be replaced, not merged\");\n}\n\nfunction t_primitives_override() {\n const result = deepMerge(\n { a: 1, b: \"old\", c: true },\n { b: \"new\", c: false, d: null },\n );\n deepEqual(result, { a: 1, b: \"new\", c: false, d: null }, \"primitives override\");\n}\n\nfunction t_deep_three_levels() {\n const result = deepMerge(\n { l1: { l2: { l3a: 1, keep: \"x\" } } },\n { l1: { l2: { l3b: 2 } } },\n );\n deepEqual(\n result,\n { l1: { l2: { l3a: 1, keep: \"x\", l3b: 2 } } },\n \"three-level nested merge\",\n );\n}\n\nfunction t_empty_json_defaults() {\n const config = loadConfig(\"{}\");\n deepEqual(config, DEFAULTS, \"empty overrides must reproduce defaults\");\n}\n\ncheck(\"merge::proto_key_does_not_pollute\", t_proto_key_does_not_pollute);\ncheck(\"merge::nested_proto_key_does_not_pollute\", t_nested_proto_key_does_not_pollute);\ncheck(\"merge::result_prototype_intact\", t_result_prototype_intact);\ncheck(\"config::defaults_not_mutated_across_loads\", t_defaults_not_mutated_across_loads);\ncheck(\"merge::basic_nested_merge\", t_basic_nested_merge);\ncheck(\"merge::arrays_replaced\", t_arrays_replaced);\ncheck(\"merge::primitives_override\", t_primitives_override);\ncheck(\"merge::deep_three_levels\", t_deep_three_levels);\ncheck(\"config::empty_json_defaults\", t_empty_json_defaults);\n\nprocess.exit(report());\n"}, {"filename": "tap.ts", "content": "/** Minimal TAP-style test helper. */\n\ninterface Result {\n ok: boolean;\n name: string;\n diag?: string;\n}\n\nconst results: Result[] = [];\n\nexport function check(name: string, fn: () => void): void {\n try {\n fn();\n results.push({ ok: true, name });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n results.push({ ok: false, name, diag: message });\n }\n}\n\nexport function assert(cond: unknown, message?: string): void {\n if (!cond) {\n throw new Error(message || \"assertion failed\");\n }\n}\n\nexport function deepEqual(actual: unknown, expected: unknown, message?: string): void {\n const a = JSON.stringify(actual);\n const b = JSON.stringify(expected);\n if (a !== b) {\n throw new Error(`${message || \"not deep equal\"}: got ${a}, want ${b}`);\n }\n}\n\nexport function report(): number {\n let failed = 0;\n results.forEach((r, i) => {\n if (r.ok) {\n console.log(`ok ${i + 1} - ${r.name}`);\n } else {\n failed += 1;\n console.log(`not ok ${i + 1} - ${r.name}`);\n console.log(` # ${r.diag}`);\n }\n });\n return failed === 0 ? 0 : 1;\n}\n"}], "gold_patch": "--- a/src/merge.ts\n+++ b/src/merge.ts\n@@ -1,22 +1,71 @@\n-/** Deep merge for configuration documents. */\n+/** Deep merge for configuration documents.\n+ *\n+ * Keys that arrive from a parsed JSON document are DATA keys. They must be\n+ * applied as own properties and never written through inherited accessors:\n+ * `key in target` is true for inherited properties, and `target[\"__proto__\"]`\n+ * resolves the prototype accessor to Object.prototype, so walking source\n+ * keys with `in` and assigning directly lets an override document pollute\n+ * every object in the process. The merge below only ever reads own\n+ * properties, copies through `Object.defineProperty` for sensitive keys,\n+ * and builds a fresh result instead of mutating its inputs.\n+ */\n \n import type { Json, JsonObject } from \"./types.ts\";\n import { isJsonObject } from \"./types.ts\";\n+\n+const SENSITIVE_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n+\n+function hasOwn(obj: object, key: string): boolean {\n+ return Object.prototype.hasOwnProperty.call(obj, key);\n+}\n+\n+function cloneObject(value: JsonObject): JsonObject {\n+ const copy: JsonObject = {};\n+ for (const key of Object.keys(value)) {\n+ copy[key] = isJsonObject(value[key])\n+ ? cloneObject(value[key])\n+ : value[key];\n+ }\n+ return copy;\n+}\n \n export function deepMerge(\n target: JsonObject,\n source: JsonObject,\n ): JsonObject {\n+ const result: JsonObject = {};\n+\n+ // Copy only OWN enumerable keys of the target.\n+ for (const key of Object.keys(target)) {\n+ result[key] = isJsonObject(target[key])\n+ ? cloneObject(target[key])\n+ : target[key];\n+ }\n+\n for (const key of Object.keys(source)) {\n const incoming = source[key];\n- if (isJsonObject(incoming)) {\n- if (!(key in target) || !isJsonObject(target[key])) {\n- target[key] = {};\n- }\n- deepMerge(target[key] as JsonObject, incoming);\n+ if (SENSITIVE_KEYS.has(key)) {\n+ // Data key with a dangerous name: define it as an inert own property\n+ // so it can never touch any prototype chain.\n+ Object.defineProperty(result, key, {\n+ value: incoming,\n+ writable: true,\n+ enumerable: true,\n+ configurable: true,\n+ });\n+ continue;\n+ }\n+ if (\n+ isJsonObject(incoming) &&\n+ hasOwn(result, key) &&\n+ isJsonObject(result[key])\n+ ) {\n+ result[key] = deepMerge(result[key], incoming);\n+ } else if (isJsonObject(incoming)) {\n+ result[key] = deepMerge({}, incoming);\n } else {\n- target[key] = incoming;\n+ result[key] = incoming;\n }\n }\n- return target;\n+ return result;\n }\n", "test_command": ["node", "tests/run_tests.ts"], "fail_to_pass": ["merge::proto_key_does_not_pollute", "merge::nested_proto_key_does_not_pollute", "merge::result_prototype_intact", "config::defaults_not_mutated_across_loads"], "pass_to_pass": ["merge::basic_nested_merge", "merge::arrays_replaced", "merge::primitives_override", "merge::deep_three_levels", "config::empty_json_defaults"], "time_limit_s": 60, "sandbox_image": "node:22-slim", "sandbox_system_deps": []}