noodcon mondk commited on
Commit
cb0011e
·
0 Parent(s):

Duplicate from mondk/SWE-DockerLess

Browse files

Co-authored-by: mon-dark <mondk@users.noreply.huggingface.co>

Files changed (44) hide show
  1. .gitattributes +60 -0
  2. README.md +120 -0
  3. SWE-DockerLess.jsonl +4 -0
  4. build_dataset.py +355 -0
  5. fixed/cronlite/cronlite/fields.py +82 -0
  6. fixed/miniconf/miniconf/config.py +92 -0
  7. fixed/semverlite/semverlite/range.py +80 -0
  8. fixed/semverlite/semverlite/version.py +96 -0
  9. fixed/ttlcache/ttlcache/cache.py +94 -0
  10. newtests/cronlite/tests/test_step_and_sunday.py +43 -0
  11. newtests/miniconf/tests/test_interpolation_edge_cases.py +64 -0
  12. newtests/semverlite/tests/test_prerelease_precedence.py +55 -0
  13. newtests/ttlcache/tests/test_lru_semantics.py +55 -0
  14. predictions/cross.jsonl +4 -0
  15. predictions/empty.jsonl +4 -0
  16. predictions/partial.jsonl +4 -0
  17. reports/cross.json +45 -0
  18. reports/empty.json +45 -0
  19. reports/gold.json +49 -0
  20. reports/partial.json +66 -0
  21. repos/cronlite/README.md +43 -0
  22. repos/cronlite/cronlite/__init__.py +27 -0
  23. repos/cronlite/cronlite/expr.py +59 -0
  24. repos/cronlite/cronlite/fields.py +74 -0
  25. repos/cronlite/tests/test_basic.py +98 -0
  26. repos/miniconf/README.md +52 -0
  27. repos/miniconf/miniconf/__init__.py +21 -0
  28. repos/miniconf/miniconf/config.py +67 -0
  29. repos/miniconf/miniconf/errors.py +30 -0
  30. repos/miniconf/miniconf/loader.py +14 -0
  31. repos/miniconf/tests/test_basic.py +82 -0
  32. repos/semverlite/README.md +45 -0
  33. repos/semverlite/semverlite/__init__.py +8 -0
  34. repos/semverlite/semverlite/range.py +71 -0
  35. repos/semverlite/semverlite/version.py +84 -0
  36. repos/semverlite/tests/test_version.py +106 -0
  37. repos/ttlcache/README.md +40 -0
  38. repos/ttlcache/tests/test_cache.py +111 -0
  39. repos/ttlcache/ttlcache/__init__.py +8 -0
  40. repos/ttlcache/ttlcache/cache.py +83 -0
  41. repos/ttlcache/ttlcache/clock.py +28 -0
  42. run_harness.py +238 -0
  43. tools/make_controls.py +168 -0
  44. tools/validate.py +174 -0
.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - swe
7
+ - dockerless
8
+ configs:
9
+ - config_name: swe
10
+ data_files: "SWE-DockerLess.jsonl"
11
+ ---
12
+ # SWE-DockerLess
13
+
14
+ A SWE-bench-shaped benchmark that needs **no Docker, no network and no prebuilt
15
+ image**. Every row carries its own repo snapshot, so an instance is reproduced by
16
+ writing files to a temp directory, `git init`, `git apply` and running pytest.
17
+
18
+ Rows are byte-for-byte SWE-bench compatible: same field names, same
19
+ `FAIL_TO_PASS` / `PASS_TO_PASS` JSON-string encoding, same "resolved" rule. One
20
+ extra `dockerless` object carries the snapshot and the test command.
21
+
22
+ ```
23
+ SWE-DockerLess.jsonl 4 instances, 62.9 KiB (~16k tokens total)
24
+ build_dataset.py rebuilds the jsonl from repos/ + fixed/ + newtests/ and
25
+ derives F2P/P2P by actually running pytest
26
+ run_harness.py scoring harness (--gold, or --predictions preds.jsonl)
27
+ repos/ the four buggy base repos (the source of the snapshots)
28
+ fixed/ gold-fix versions of the touched files
29
+ newtests/ the tests that become test_patch
30
+ tools/validate.py schema, patch-application and budget checks
31
+ tools/make_controls.py generates empty / cross / partial negative controls
32
+ reports/ harness output for gold and the three controls
33
+ ```
34
+
35
+ ## Instances
36
+
37
+ | instance_id | repo | the bug | F2P | P2P | gold patch |
38
+ | --- | --- | --- | --- | --- | --- |
39
+ | `swedl__miniconf-1` | swedl/miniconf | `${k}` interpolation recurses on cycles (no `CircularReferenceError`) and `$$` never escapes | 9 | 15 | 41 added lines |
40
+ | `swedl__ttlcache-1` | swedl/ttlcache | LRU order ignores reads and overwrites; `len()` counts expired rows | 5 | 12 | 12 added lines |
41
+ | `swedl__cronlite-1` | swedl/cronlite | `5/15` collapses to `{5}`; day-of-week `7` rejected | 8 | 21 | 11 added lines |
42
+ | `swedl__semverlite-1` | swedl/semverlite | prerelease ordering is lexicographic; prereleases satisfy release ranges | 7 | 19 | 23 added lines |
43
+
44
+ 29 FAIL_TO_PASS tests, 67 PASS_TO_PASS tests. Difficulty is SWE-bench-like rather
45
+ than toy-like: each fix needs a behaviour change in a real algorithm (recursive
46
+ descent with cycle detection, an LRU invariant, cron field expansion, semver
47
+ precedence), and the hidden tests pin exact semantics — error message text, the
48
+ 0-6 weekday scale, the "prerelease must opt in" range rule — that a shallow
49
+ patch misses. The `partial` control below scores 5/9, 2/5, 6/8 and 3/7 F2P
50
+ without resolving a single instance.
51
+
52
+ ## Row schema
53
+
54
+ | field | notes |
55
+ | --- | --- |
56
+ | `instance_id` | `swedl__<repo>-1` |
57
+ | `repo` | `swedl/<repo>` |
58
+ | `base_commit` | real 40-char sha of the snapshot commit (deterministic) |
59
+ | `patch` | gold fix, `git diff` unified diff against `base_commit` |
60
+ | `test_patch` | adds test files only, never touches source |
61
+ | `problem_statement` | issue-style report; states the contract, never names a test |
62
+ | `hints_text` | `""` |
63
+ | `created_at`, `version` | `2026-10-30`, `1.0` |
64
+ | `environment_setup_commit` | equals `base_commit` |
65
+ | `FAIL_TO_PASS`, `PASS_TO_PASS` | JSON-encoded strings, as in SWE-bench |
66
+ | `dockerless.files` | `{path: content}` snapshot of the repo at `base_commit` |
67
+ | `dockerless.test_cmd` | `python -m pytest -v --tb=no -p no:cacheprovider {tests}` |
68
+ | `dockerless.test_files` | the node-id prefixes to run |
69
+
70
+ ## Running it
71
+
72
+ ```bash
73
+ python -m pip install pytest # the only dependency
74
+ python build_dataset.py # regenerate + re-verify the jsonl
75
+ python run_harness.py --gold # sanity check, expect 4/4
76
+ python run_harness.py --predictions predictions/partial.jsonl --out reports/partial.json
77
+ ```
78
+
79
+ A predictions file is JSONL of `{"instance_id", "model_name_or_path",
80
+ "model_patch"}` — the SWE-bench format. `resolved` requires **all** F2P and
81
+ **all** P2P to pass.
82
+
83
+ ## Verified results
84
+
85
+ ```
86
+ $ python run_harness.py --gold
87
+ instance resolved F2P P2P note
88
+ swedl__miniconf-1 yes 9/9 15/15 ok
89
+ swedl__ttlcache-1 yes 5/5 12/12 ok
90
+ swedl__cronlite-1 yes 8/8 21/21 ok
91
+ swedl__semverlite-1 yes 7/7 19/19 ok
92
+ resolved 4/4 (100.0%) in 10.3s
93
+
94
+ $ python run_harness.py --predictions predictions/empty.jsonl -> 0/4
95
+ $ python run_harness.py --predictions predictions/cross.jsonl -> 0/4
96
+ $ python run_harness.py --predictions predictions/partial.jsonl -> 0/4
97
+ ```
98
+
99
+ `build_dataset.py` is the ground truth for F2P/P2P: it materialises a clean
100
+ checkout, applies `test_patch`, runs pytest, applies `patch`, runs pytest again,
101
+ and classifies every test by observed outcome. It refuses to write a row if the
102
+ gold patch leaves any failure behind, if F2P is empty, or if a test disappears.
103
+
104
+ ## Budget
105
+
106
+ Measured for `max_tokens = 2048`, `context = 240000`:
107
+
108
+ - prompt per instance: ~2.0k–2.6k tokens (problem statement + snapshot)
109
+ - gold patch: 11–41 added lines, ~200–700 tokens — comfortably inside 2048
110
+ - whole dataset: ~16k tokens, so all four rows fit in one context if you want
111
+
112
+ ## Deliberate deviations from SWE-bench
113
+
114
+ - **Synthetic repos.** These are four purpose-built Python packages, not real
115
+ GitHub projects, so there is no `repo` clone step and no upstream history.
116
+ - **Snapshot in the row** instead of a Docker image. `base_commit` is a genuine
117
+ commit sha of that snapshot, so `git apply` and `git diff` behave normally.
118
+ - **No install step.** Packages are importable from the repo root, so
119
+ `dockerless.install` is empty and pytest runs with the repo as rootdir.
120
+ - **Python only**, single language, to keep the harness to `python + git + pytest`.
SWE-DockerLess.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"instance_id": "swedl__miniconf-1", "repo": "swedl/miniconf", "base_commit": "f7b5b3a4cfec71e8e6db94c76ae5c4e2ea509216", "patch": "diff --git a/miniconf/config.py b/miniconf/config.py\nindex 8751912..6bdf695 100644\n--- a/miniconf/config.py\n+++ b/miniconf/config.py\n@@ -1,12 +1,8 @@\n \"\"\"The Config object: layered key/value storage with ${...} interpolation.\"\"\"\n \n-import re\n-\n-from .errors import MissingKeyError\n+from .errors import CircularReferenceError, MissingKeyError\n from .loader import load_layers\n \n-REFERENCE = re.compile(r\"\\$\\{([A-Za-z_][A-Za-z0-9_.-]*)\\}\")\n-\n \n class Config:\n \"\"\"A small configuration mapping whose string values may reference keys.\n@@ -51,17 +47,46 @@ class Config:\n \"\"\"Return every key resolved to a plain value.\"\"\"\n return {key: self._resolve(key) for key in self._raw}\n \n- def _resolve(self, key):\n+ def _resolve(self, key, stack=()):\n+ if key in stack:\n+ cycle = stack[stack.index(key):] + (key,)\n+ raise CircularReferenceError(cycle)\n+ if key not in self._raw:\n+ raise MissingKeyError(key, stack[-1] if stack else None)\n value = self._raw[key]\n if not isinstance(value, str):\n return value\n- return self._interpolate(value, key)\n-\n- def _interpolate(self, text, origin):\n- def replace(match):\n- name = match.group(1)\n- if name not in self._raw:\n- raise MissingKeyError(name, origin)\n- return str(self._resolve(name))\n-\n- return REFERENCE.sub(replace, text)\n+ return self._render(value, stack + (key,))\n+\n+ def _render(self, text, stack):\n+ \"\"\"Resolve references in ``text`` in a single left-to-right pass.\"\"\"\n+ out = []\n+ index = 0\n+ length = len(text)\n+ while index < length:\n+ char = text[index]\n+ if char != \"$\":\n+ out.append(char)\n+ index += 1\n+ continue\n+ if text.startswith(\"$$\", index):\n+ out.append(\"$\")\n+ index += 2\n+ continue\n+ if text.startswith(\"${\", index):\n+ end = text.find(\"}\", index + 2)\n+ if end == -1:\n+ out.append(char)\n+ index += 1\n+ continue\n+ name = text[index + 2:end]\n+ if not name:\n+ out.append(char)\n+ index += 1\n+ continue\n+ out.append(str(self._resolve(name, stack)))\n+ index = end + 1\n+ continue\n+ out.append(char)\n+ index += 1\n+ return \"\".join(out)\n", "test_patch": "diff --git a/tests/test_interpolation_edge_cases.py b/tests/test_interpolation_edge_cases.py\nnew file mode 100644\nindex 0000000..6289238\n--- /dev/null\n+++ b/tests/test_interpolation_edge_cases.py\n@@ -0,0 +1,64 @@\n+import pytest\n+\n+from miniconf import CircularReferenceError, Config, MissingKeyError\n+\n+\n+def test_dollar_escape():\n+ cfg = Config({\"price\": \"$${amount}\"})\n+ assert cfg[\"price\"] == \"${amount}\"\n+\n+\n+def test_escape_next_to_reference():\n+ cfg = Config({\"name\": \"wren\", \"msg\": \"$${name} is ${name}\"})\n+ assert cfg[\"msg\"] == \"${name} is wren\"\n+\n+\n+def test_self_reference():\n+ cfg = Config({\"a\": \"x${a}\"})\n+ with pytest.raises(CircularReferenceError):\n+ cfg[\"a\"]\n+\n+\n+def test_as_dict_raises_on_cycle():\n+ cfg = Config({\"a\": \"${b}\", \"b\": \"${a}\"})\n+ with pytest.raises(CircularReferenceError):\n+ cfg.as_dict()\n+\n+\n+def test_cycle_not_involving_requested_key():\n+ cfg = Config({\"a\": \"fine\", \"b\": \"${c}\", \"c\": \"${b}\"})\n+ assert cfg[\"a\"] == \"fine\"\n+ with pytest.raises(CircularReferenceError):\n+ cfg[\"b\"]\n+\n+\n+def test_two_cycle_chain_starts_at_requested_key():\n+ cfg = Config({\"a\": \"${b}\", \"b\": \"${a}\"})\n+ with pytest.raises(CircularReferenceError) as excinfo:\n+ cfg[\"a\"]\n+ assert str(excinfo.value) == \"circular reference: a -> b -> a\"\n+\n+\n+def test_self_reference_message():\n+ cfg = Config({\"loop\": \"${loop}\"})\n+ with pytest.raises(CircularReferenceError) as excinfo:\n+ cfg[\"loop\"]\n+ assert str(excinfo.value) == \"circular reference: loop -> loop\"\n+\n+\n+def test_escaped_text_is_not_reinterpolated_through_a_reference():\n+ cfg = Config({\"inner\": \"$${leak}\", \"outer\": \"${inner}\"})\n+ assert cfg[\"outer\"] == \"${leak}\"\n+\n+\n+def test_missing_key_inside_reference_chain():\n+ cfg = Config({\"a\": \"${b}\", \"b\": \"${nope}\"})\n+ with pytest.raises(MissingKeyError) as excinfo:\n+ cfg[\"a\"]\n+ assert str(excinfo.value) == \"missing key 'nope' referenced from 'b'\"\n+\n+\n+def test_escape_does_not_hide_a_real_cycle():\n+ cfg = Config({\"a\": \"$${b}\", \"b\": \"${a}\"})\n+ assert cfg[\"a\"] == \"${b}\"\n+ assert cfg[\"b\"] == \"${b}\"\n", "problem_statement": "Config interpolation blows up on reference cycles and expands escaped text.\n\nWe use miniconf for service configs that are layered from a shared file plus a\nper-environment overlay. Two problems, both reproducible on main:\n\n1. A cycle anywhere in the mapping crashes with `RecursionError` instead of the\n documented error. `Config({'a': '${b}', 'b': '${a}'})['a']` recurses until the\n interpreter gives up, and the traceback is a thousand frames of `_interpolate`.\n The README says this must raise `CircularReferenceError` with a message naming\n the chain, and we rely on that message in our error reporting.\n\n2. `$$` does not escape. Our TLS config has `cert_subject: \"$${cluster}\"`, meaning\n the literal text `${cluster}` to be handed to a downstream templating tool, but\n miniconf substitutes the cluster name into it. The README's escape rule is not\n implemented at all.\n\nBoth bugs live in `Config._resolve` / `Config._interpolate` in\n`miniconf/config.py`. `README.md` section \"Interpolation contract\" is the spec we\nwant honoured, including the exact wording of the cycle message and the rule that\nsubstituted text is never rescanned for references. A cycle that is unrelated to\nthe key being read must not affect that read, and `as_dict()` must surface cycles\nlike any other read.\n\nThe existing suite passes; the escape and cycle behaviour was never covered.", "hints_text": "", "created_at": "2026-10-30", "version": "1.0", "environment_setup_commit": "f7b5b3a4cfec71e8e6db94c76ae5c4e2ea509216", "FAIL_TO_PASS": "[\"tests/test_interpolation_edge_cases.py::test_as_dict_raises_on_cycle\", \"tests/test_interpolation_edge_cases.py::test_cycle_not_involving_requested_key\", \"tests/test_interpolation_edge_cases.py::test_dollar_escape\", \"tests/test_interpolation_edge_cases.py::test_escape_does_not_hide_a_real_cycle\", \"tests/test_interpolation_edge_cases.py::test_escape_next_to_reference\", \"tests/test_interpolation_edge_cases.py::test_escaped_text_is_not_reinterpolated_through_a_reference\", \"tests/test_interpolation_edge_cases.py::test_self_reference\", \"tests/test_interpolation_edge_cases.py::test_self_reference_message\", \"tests/test_interpolation_edge_cases.py::test_two_cycle_chain_starts_at_requested_key\"]", "PASS_TO_PASS": "[\"tests/test_basic.py::test_as_dict_resolves_all\", \"tests/test_basic.py::test_chained_reference\", \"tests/test_basic.py::test_config_rejects_non_dict\", \"tests/test_basic.py::test_from_layers_override\", \"tests/test_basic.py::test_get_returns_default_for_unknown_key\", \"tests/test_basic.py::test_getitem_raises_keyerror_for_unknown_key\", \"tests/test_basic.py::test_load_layers_rejects_non_dict\", \"tests/test_basic.py::test_missing_key_message\", \"tests/test_basic.py::test_missing_key_raises\", \"tests/test_basic.py::test_non_string_passthrough\", \"tests/test_basic.py::test_plain_values\", \"tests/test_basic.py::test_raw_does_not_resolve\", \"tests/test_basic.py::test_simple_reference\", \"tests/test_basic.py::test_two_references_in_one_value\", \"tests/test_interpolation_edge_cases.py::test_missing_key_inside_reference_chain\"]", "dockerless": {"language": "python", "python_requires": ">=3.9", "install": [], "run_from": ".", "test_cmd": "python -m pytest -v --tb=no -p no:cacheprovider {tests}", "test_files": ["tests/test_basic.py", "tests/test_interpolation_edge_cases.py"], "files": {"miniconf/__init__.py": "\"\"\"miniconf - a tiny layered configuration library with string interpolation.\"\"\"\n\nfrom .config import Config\nfrom .errors import (\n CircularReferenceError,\n ConfigError,\n InterpolationError,\n MissingKeyError,\n)\nfrom .loader import load_layers\n\n__version__ = \"0.4.1\"\n\n__all__ = [\n \"CircularReferenceError\",\n \"Config\",\n \"ConfigError\",\n \"InterpolationError\",\n \"MissingKeyError\",\n \"load_layers\",\n]\n", "miniconf/config.py": "\"\"\"The Config object: layered key/value storage with ${...} interpolation.\"\"\"\n\nimport re\n\nfrom .errors import MissingKeyError\nfrom .loader import load_layers\n\nREFERENCE = re.compile(r\"\\$\\{([A-Za-z_][A-Za-z0-9_.-]*)\\}\")\n\n\nclass Config:\n \"\"\"A small configuration mapping whose string values may reference keys.\n\n See README.md for the interpolation contract.\n \"\"\"\n\n def __init__(self, data):\n if not isinstance(data, dict):\n raise TypeError(\"Config data must be a dict\")\n self._raw = dict(data)\n\n @classmethod\n def from_layers(cls, *layers):\n \"\"\"Build a Config from one or more dict layers, later layers winning.\"\"\"\n return cls(load_layers(*layers))\n\n def raw(self, key, default=None):\n \"\"\"Return the unresolved value stored under ``key``.\"\"\"\n return self._raw.get(key, default)\n\n def keys(self):\n return list(self._raw)\n\n def get(self, key, default=None):\n if key not in self._raw:\n return default\n return self._resolve(key)\n\n def __getitem__(self, key):\n if key not in self._raw:\n raise KeyError(key)\n return self._resolve(key)\n\n def __contains__(self, key):\n return key in self._raw\n\n def __len__(self):\n return len(self._raw)\n\n def as_dict(self):\n \"\"\"Return every key resolved to a plain value.\"\"\"\n return {key: self._resolve(key) for key in self._raw}\n\n def _resolve(self, key):\n value = self._raw[key]\n if not isinstance(value, str):\n return value\n return self._interpolate(value, key)\n\n def _interpolate(self, text, origin):\n def replace(match):\n name = match.group(1)\n if name not in self._raw:\n raise MissingKeyError(name, origin)\n return str(self._resolve(name))\n\n return REFERENCE.sub(replace, text)\n", "miniconf/errors.py": "\"\"\"Exception hierarchy for miniconf.\"\"\"\n\n\nclass ConfigError(Exception):\n \"\"\"Base class for every error raised by miniconf.\"\"\"\n\n\nclass InterpolationError(ConfigError):\n \"\"\"Raised when a ``${...}`` reference cannot be resolved.\"\"\"\n\n\nclass MissingKeyError(InterpolationError):\n \"\"\"Raised when a reference points at a key that does not exist.\"\"\"\n\n def __init__(self, key, referenced_from=None):\n self.key = key\n self.referenced_from = referenced_from\n if referenced_from is None:\n message = \"missing key: %r\" % (key,)\n else:\n message = \"missing key %r referenced from %r\" % (key, referenced_from)\n super().__init__(message)\n\n\nclass CircularReferenceError(InterpolationError):\n \"\"\"Raised when interpolation would loop forever.\"\"\"\n\n def __init__(self, cycle):\n self.cycle = list(cycle)\n super().__init__(\"circular reference: \" + \" -> \".join(self.cycle))\n", "miniconf/loader.py": "\"\"\"Layer merging for miniconf configuration dicts.\"\"\"\n\nfrom .errors import ConfigError\n\n\ndef load_layers(*layers):\n \"\"\"Merge configuration layers left to right; later layers win.\"\"\"\n merged = {}\n for layer in layers:\n if not isinstance(layer, dict):\n raise ConfigError(\"layer must be a dict, got %r\" % (type(layer).__name__,))\n for key, value in layer.items():\n merged[key] = value\n return merged\n", "README.md": "# miniconf\n\nA tiny layered configuration library. Values may reference other keys with\n`${key}` and are resolved lazily on access.\n\n## Interpolation contract\n\nThis is the documented behaviour of `Config`; `tests/` covers the common cases.\n\n1. **References.** A string value may contain any number of `${key}` references.\n The reference is replaced by the *fully resolved* value of `key`, stringified\n with `str()`. References may chain: `a` -> `b` -> `c`.\n2. **Single pass.** Substituted text is never scanned again for references. If\n `inner` resolves to the literal text `${leak}`, then `\"${inner}\"` resolves to\n `${leak}` and not to the value of `leak`.\n3. **Escaping.** `$$` is an escape that produces a single literal `$`. It never\n starts a reference, so `\"$${amount}\"` resolves to the five characters\n `${amount}` — the reference is *not* expanded. `\"$${name} is ${name}\"` with\n `name=wren` resolves to `\"${name} is wren\"`.\n4. **Cycles.** A reference cycle, including a self reference such as\n `a = \"x${a}\"`, must raise `CircularReferenceError` instead of recursing. The\n message is `\"circular reference: \"` followed by the key chain joined with\n `\" -> \"`, starting at the key the caller asked for and ending with that same\n key repeated. Asking for `a` where `a -> b -> a` raises\n `\"circular reference: a -> b -> a\"`; asking for `a` where `a -> a` raises\n `\"circular reference: a -> a\"`.\n5. **Missing keys.** A reference to an unknown key raises `MissingKeyError`.\n6. **Non-string values** are returned as-is and are never scanned.\n\n`Config.as_dict()` resolves every key, so any cycle or missing reference in the\nmapping surfaces there too. A cycle that is unrelated to the key being read must\nnot affect that read: with `a=\"fine\"`, `b=\"${c}\"`, `c=\"${b}\"`, reading `a` still\nreturns `\"fine\"` while reading `b` raises.\n\n## Usage\n\n```python\nfrom miniconf import Config\n\ncfg = Config.from_layers(\n {\"host\": \"localhost\", \"port\": 8080},\n {\"url\": \"http://${host}:${port}/\"},\n)\ncfg[\"url\"] # 'http://localhost:8080/'\ncfg.as_dict() # {'host': 'localhost', 'port': 8080, 'url': 'http://localhost:8080/'}\n```\n\n## Tests\n\n```\npython -m pytest -q\n```\n", "tests/test_basic.py": "import pytest\n\nfrom miniconf import Config, ConfigError, MissingKeyError, load_layers\n\n\ndef test_plain_values():\n cfg = Config({\"name\": \"app\", \"port\": 8080})\n assert cfg[\"name\"] == \"app\"\n assert cfg[\"port\"] == 8080\n assert len(cfg) == 2\n\n\ndef test_simple_reference():\n cfg = Config({\"host\": \"localhost\", \"url\": \"http://${host}/\"})\n assert cfg[\"url\"] == \"http://localhost/\"\n\n\ndef test_two_references_in_one_value():\n cfg = Config({\"host\": \"db\", \"port\": 5432, \"dsn\": \"${host}:${port}\"})\n assert cfg[\"dsn\"] == \"db:5432\"\n\n\ndef test_chained_reference():\n cfg = Config({\"a\": \"x\", \"b\": \"${a}-y\", \"c\": \"${b}-z\"})\n assert cfg[\"c\"] == \"x-y-z\"\n\n\ndef test_missing_key_raises():\n cfg = Config({\"a\": \"${nope}\"})\n with pytest.raises(MissingKeyError):\n cfg[\"a\"]\n\n\ndef test_missing_key_message():\n cfg = Config({\"a\": \"${nope}\"})\n with pytest.raises(MissingKeyError) as excinfo:\n cfg[\"a\"]\n assert str(excinfo.value) == \"missing key 'nope' referenced from 'a'\"\n\n\ndef test_non_string_passthrough():\n cfg = Config({\"n\": 3, \"flag\": True, \"nested\": {\"x\": 1}})\n assert cfg[\"n\"] == 3\n assert cfg[\"flag\"] is True\n assert cfg[\"nested\"] == {\"x\": 1}\n\n\ndef test_get_returns_default_for_unknown_key():\n cfg = Config({\"a\": \"1\"})\n assert cfg.get(\"zzz\") is None\n assert cfg.get(\"zzz\", \"dflt\") == \"dflt\"\n\n\ndef test_getitem_raises_keyerror_for_unknown_key():\n cfg = Config({\"a\": \"1\"})\n with pytest.raises(KeyError):\n cfg[\"zzz\"]\n\n\ndef test_raw_does_not_resolve():\n cfg = Config({\"a\": \"1\", \"b\": \"${a}\"})\n assert cfg.raw(\"b\") == \"${a}\"\n\n\ndef test_from_layers_override():\n cfg = Config.from_layers({\"a\": \"1\", \"b\": \"2\"}, {\"b\": \"3\"})\n assert cfg.as_dict() == {\"a\": \"1\", \"b\": \"3\"}\n\n\ndef test_load_layers_rejects_non_dict():\n with pytest.raises(ConfigError):\n load_layers({\"a\": 1}, [\"not\", \"a\", \"dict\"])\n\n\ndef test_as_dict_resolves_all():\n cfg = Config({\"a\": \"1\", \"b\": \"${a}2\"})\n assert cfg.as_dict() == {\"a\": \"1\", \"b\": \"12\"}\n\n\ndef test_config_rejects_non_dict():\n with pytest.raises(TypeError):\n Config([(\"a\", 1)])\n"}}}
2
+ {"instance_id": "swedl__ttlcache-1", "repo": "swedl/ttlcache", "base_commit": "7c1d3594fec009ac3cf7ef48506ec6d3b0d56132", "patch": "diff --git a/ttlcache/cache.py b/ttlcache/cache.py\nindex fda1724..4c36ad4 100644\n--- a/ttlcache/cache.py\n+++ b/ttlcache/cache.py\n@@ -28,8 +28,15 @@ class TTLCache:\n def _expired(deadline, now):\n return now >= deadline\n \n+ def _purge(self, now):\n+ \"\"\"Drop every expired entry so it can never be counted or evicted.\"\"\"\n+ stale = [key for key, (_, deadline) in self._data.items() if self._expired(deadline, now)]\n+ for key in stale:\n+ del self._data[key]\n+\n def __len__(self):\n- return len(self._data)\n+ now = self._now()\n+ return sum(1 for _, deadline in self._data.values() if not self._expired(deadline, now))\n \n def __contains__(self, key):\n if key not in self._data:\n@@ -39,6 +46,9 @@ class TTLCache:\n \n def __setitem__(self, key, value):\n now = self._now()\n+ self._purge(now)\n+ if key in self._data:\n+ del self._data[key]\n self._data[key] = (value, now + self.ttl)\n while len(self._data) > self.maxsize:\n self._data.popitem(last=False)\n@@ -48,6 +58,7 @@ class TTLCache:\n if self._expired(deadline, self._now()):\n del self._data[key]\n raise KeyError(key)\n+ self._data.move_to_end(key)\n return value\n \n def get(self, key, default=None):\n", "test_patch": "diff --git a/tests/test_lru_semantics.py b/tests/test_lru_semantics.py\nnew file mode 100644\nindex 0000000..1563011\n--- /dev/null\n+++ b/tests/test_lru_semantics.py\n@@ -0,0 +1,55 @@\n+from ttlcache import FakeClock, TTLCache\n+\n+\n+def test_get_refreshes_recency():\n+ clock = FakeClock()\n+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)\n+ cache[\"a\"] = 1\n+ cache[\"b\"] = 2\n+ assert cache[\"a\"] == 1\n+ cache[\"c\"] = 3\n+ assert \"a\" in cache\n+ assert \"b\" not in cache\n+\n+\n+def test_overwrite_refreshes_recency():\n+ clock = FakeClock()\n+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)\n+ cache[\"a\"] = 1\n+ cache[\"b\"] = 2\n+ cache[\"a\"] = 9\n+ cache[\"c\"] = 3\n+ assert cache[\"a\"] == 9\n+ assert \"b\" not in cache\n+\n+\n+def test_setdefault_refreshes_recency():\n+ clock = FakeClock()\n+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)\n+ cache[\"a\"] = 1\n+ cache[\"b\"] = 2\n+ assert cache.setdefault(\"a\", lambda: 99) == 1\n+ cache[\"c\"] = 3\n+ assert \"a\" in cache\n+ assert \"b\" not in cache\n+\n+\n+def test_len_ignores_expired_entries():\n+ clock = FakeClock()\n+ cache = TTLCache(maxsize=4, ttl=10.0, clock=clock)\n+ cache[\"a\"] = 1\n+ clock.advance(5)\n+ cache[\"b\"] = 2\n+ clock.advance(6)\n+ assert len(cache) == 1\n+ assert \"a\" not in cache\n+ assert \"b\" in cache\n+\n+\n+def test_items_reports_least_recently_used_first():\n+ clock = FakeClock()\n+ cache = TTLCache(maxsize=3, ttl=10.0, clock=clock)\n+ cache[\"a\"] = 1\n+ cache[\"b\"] = 2\n+ assert cache[\"a\"] == 1\n+ assert list(cache.items()) == [(\"b\", 2), (\"a\", 1)]\n", "problem_statement": "LRU eviction ignores reads, and len() counts entries that already expired.\n\nOur request cache is a `TTLCache(maxsize=N, ttl=...)` and it is evicting the wrong\nkeys under load:\n\n1. Reading a key does not protect it. With `maxsize=2`, writing `a`, `b`, reading\n `a`, then writing `c` drops `a` and keeps `b` -- the exact opposite of LRU. The\n same happens when a key is overwritten: the new write keeps the old position\n instead of becoming the most recently used entry.\n\n2. `len(cache)` returns the number of stored rows, including rows whose TTL already\n elapsed. Our metrics dashboard reports a cache that never shrinks even though\n every read says the key is gone.\n\n3. `items()` order does not reflect access order for the same reason.\n\n`README.md` documents the intended contract (sections 2-5): reads and overwrites\nmark an entry most-recently-used, expired entries are purged before eviction\nhappens, and `len()` counts live entries only. `ttlcache/cache.py` is the file to\nfix; `ttlcache/clock.py` already gives you a deterministic `FakeClock`.\n\nBe careful that expiry still deletes the entry on read and that `get()` keeps\nreturning its default for missing keys.", "hints_text": "", "created_at": "2026-10-30", "version": "1.0", "environment_setup_commit": "7c1d3594fec009ac3cf7ef48506ec6d3b0d56132", "FAIL_TO_PASS": "[\"tests/test_lru_semantics.py::test_get_refreshes_recency\", \"tests/test_lru_semantics.py::test_items_reports_least_recently_used_first\", \"tests/test_lru_semantics.py::test_len_ignores_expired_entries\", \"tests/test_lru_semantics.py::test_overwrite_refreshes_recency\", \"tests/test_lru_semantics.py::test_setdefault_refreshes_recency\"]", "PASS_TO_PASS": "[\"tests/test_cache.py::test_entry_expires\", \"tests/test_cache.py::test_entry_survives_before_deadline\", \"tests/test_cache.py::test_eviction_order_on_insert\", \"tests/test_cache.py::test_getitem_raises_for_missing_key\", \"tests/test_cache.py::test_invalid_arguments\", \"tests/test_cache.py::test_items_skips_expired\", \"tests/test_cache.py::test_missing_key_returns_default\", \"tests/test_cache.py::test_overwrite_updates_value\", \"tests/test_cache.py::test_pop_removes_entry\", \"tests/test_cache.py::test_repr_reports_live_count\", \"tests/test_cache.py::test_set_and_get\", \"tests/test_cache.py::test_setdefault_uses_factory_once\"]", "dockerless": {"language": "python", "python_requires": ">=3.9", "install": [], "run_from": ".", "test_cmd": "python -m pytest -v --tb=no -p no:cacheprovider {tests}", "test_files": ["tests/test_cache.py", "tests/test_lru_semantics.py"], "files": {"README.md": "# ttlcache\n\nA bounded cache with per-entry time-to-live and LRU eviction. The cache never\nreads the system clock directly; pass a `clock` object exposing `now()` (see\n`ttlcache.clock.FakeClock`) so expiry is deterministic under test.\n\n## Contract\n\n1. **Expiry.** An entry written at time `t` is live while `now < t + ttl` and\n expired once `now >= t + ttl`. Reading an expired key deletes it and raises\n `KeyError` (`get` returns its default instead). `key in cache` is `False` for\n expired entries.\n2. **Recency.** `__getitem__`, `get` and `setdefault` mark the entry as most\n recently used. Writing an existing key also moves it to the most-recently-used\n end *and* restarts its TTL.\n3. **Eviction.** When a write would exceed `maxsize`, expired entries are dropped\n first; if the cache is still full, the least recently used live entry is\n dropped.\n4. **`len(cache)`** counts live entries only. Expired-but-not-yet-collected\n entries must not inflate the count.\n5. **`items()`** yields live pairs in LRU order (least recently used first).\n\n## Usage\n\n```python\nfrom ttlcache import FakeClock, TTLCache\n\nclock = FakeClock()\ncache = TTLCache(maxsize=2, ttl=10.0, clock=clock)\ncache[\"a\"] = 1\ncache[\"b\"] = 2\ncache[\"a\"] # 'a' is now most recently used\ncache[\"c\"] = 3 # evicts 'b', not 'a'\n```\n\n## Tests\n\n```\npython -m pytest -q\n```\n", "tests/test_cache.py": "import pytest\n\nfrom ttlcache import FakeClock, TTLCache\n\n\ndef make(clock, maxsize=3, ttl=10.0):\n return TTLCache(maxsize=maxsize, ttl=ttl, clock=clock)\n\n\ndef test_set_and_get():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n assert cache[\"a\"] == 1\n assert cache.get(\"a\") == 1\n\n\ndef test_missing_key_returns_default():\n cache = make(FakeClock())\n assert cache.get(\"nope\") is None\n assert cache.get(\"nope\", 7) == 7\n\n\ndef test_getitem_raises_for_missing_key():\n cache = make(FakeClock())\n with pytest.raises(KeyError):\n cache[\"nope\"]\n\n\ndef test_entry_expires():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n clock.advance(10)\n assert \"a\" not in cache\n assert cache.get(\"a\") is None\n with pytest.raises(KeyError):\n cache[\"a\"]\n\n\ndef test_entry_survives_before_deadline():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n clock.advance(9.5)\n assert cache[\"a\"] == 1\n\n\ndef test_eviction_order_on_insert():\n clock = FakeClock()\n cache = make(clock, maxsize=2)\n cache[\"a\"] = 1\n cache[\"b\"] = 2\n cache[\"c\"] = 3\n assert \"a\" not in cache\n assert \"b\" in cache and \"c\" in cache\n\n\ndef test_overwrite_updates_value():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n cache[\"a\"] = 2\n assert cache[\"a\"] == 2\n assert len(cache) == 1\n\n\ndef test_setdefault_uses_factory_once():\n clock = FakeClock()\n cache = make(clock)\n calls = []\n\n def factory():\n calls.append(1)\n return \"v\"\n\n assert cache.setdefault(\"k\", factory) == \"v\"\n assert cache.setdefault(\"k\", factory) == \"v\"\n assert len(calls) == 1\n\n\ndef test_pop_removes_entry():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n assert cache.pop(\"a\") == 1\n assert cache.pop(\"a\", \"gone\") == \"gone\"\n\n\ndef test_items_skips_expired():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n clock.advance(4)\n cache[\"b\"] = 2\n clock.advance(7)\n assert list(cache.items()) == [(\"b\", 2)]\n\n\ndef test_invalid_arguments():\n with pytest.raises(ValueError):\n TTLCache(maxsize=0)\n with pytest.raises(ValueError):\n TTLCache(ttl=0)\n\n\ndef test_repr_reports_live_count():\n clock = FakeClock()\n cache = make(clock)\n cache[\"a\"] = 1\n assert \"live=1\" in repr(cache)\n", "ttlcache/__init__.py": "\"\"\"ttlcache - a bounded TTL + LRU cache.\"\"\"\n\nfrom .cache import TTLCache\nfrom .clock import FakeClock, SystemClock\n\n__version__ = \"0.3.0\"\n\n__all__ = [\"FakeClock\", \"SystemClock\", \"TTLCache\"]\n", "ttlcache/cache.py": "\"\"\"A bounded cache with per-entry time-to-live and LRU eviction.\"\"\"\n\nfrom collections import OrderedDict\n\n\nclass TTLCache:\n \"\"\"Fixed-capacity cache where every entry expires ``ttl`` seconds after write.\n\n Entries are kept in least-recently-used order. When the cache is full the\n least recently used entry is dropped first. See README.md for the full\n contract.\n \"\"\"\n\n def __init__(self, maxsize=128, ttl=60.0, clock=None):\n if maxsize <= 0:\n raise ValueError(\"maxsize must be positive\")\n if ttl <= 0:\n raise ValueError(\"ttl must be positive\")\n self.maxsize = maxsize\n self.ttl = float(ttl)\n self._clock = clock\n self._data = OrderedDict()\n\n def _now(self):\n return self._clock.now() if self._clock is not None else 0.0\n\n @staticmethod\n def _expired(deadline, now):\n return now >= deadline\n\n def __len__(self):\n return len(self._data)\n\n def __contains__(self, key):\n if key not in self._data:\n return False\n _, deadline = self._data[key]\n return not self._expired(deadline, self._now())\n\n def __setitem__(self, key, value):\n now = self._now()\n self._data[key] = (value, now + self.ttl)\n while len(self._data) > self.maxsize:\n self._data.popitem(last=False)\n\n def __getitem__(self, key):\n value, deadline = self._data[key]\n if self._expired(deadline, self._now()):\n del self._data[key]\n raise KeyError(key)\n return value\n\n def get(self, key, default=None):\n try:\n return self[key]\n except KeyError:\n return default\n\n def setdefault(self, key, factory):\n \"\"\"Return the live value for ``key``, computing and storing it if absent.\"\"\"\n if key in self:\n return self[key]\n value = factory()\n self[key] = value\n return value\n\n def pop(self, key, default=None):\n if key not in self._data:\n return default\n value, _ = self._data.pop(key)\n return value\n\n def items(self):\n \"\"\"Iterate over live ``(key, value)`` pairs in LRU order.\"\"\"\n now = self._now()\n return [(k, v) for k, (v, d) in self._data.items() if not self._expired(d, now)]\n\n def __repr__(self):\n return \"TTLCache(maxsize=%d, ttl=%r, live=%d)\" % (\n self.maxsize,\n self.ttl,\n len(self),\n )\n", "ttlcache/clock.py": "\"\"\"Clocks used by ttlcache.\n\nThe cache never calls ``time`` directly: it asks a clock object for the current\ntime, which makes expiry deterministic in tests.\n\"\"\"\n\nimport time\n\n\nclass SystemClock:\n \"\"\"Monotonic wall clock for production use.\"\"\"\n\n def now(self):\n return time.monotonic()\n\n\nclass FakeClock:\n \"\"\"A clock that only moves when you tell it to.\"\"\"\n\n def __init__(self, start=0.0):\n self._now = float(start)\n\n def now(self):\n return self._now\n\n def advance(self, seconds):\n self._now += float(seconds)\n return self._now\n"}}}
3
+ {"instance_id": "swedl__cronlite-1", "repo": "swedl/cronlite", "base_commit": "cb8cd4f111a02d9358774debe834b530bcbfeb94", "patch": "diff --git a/cronlite/fields.py b/cronlite/fields.py\nindex 4945d5e..b3c0eb6 100644\n--- a/cronlite/fields.py\n+++ b/cronlite/fields.py\n@@ -1,13 +1,19 @@\n \"\"\"Parsing of individual cron fields into sets of integers.\"\"\"\n \n \n+def _sunday_alias(value):\n+ \"\"\"Collapse the cron Sunday alias 7 onto 0.\"\"\"\n+ return 0 if value == 7 else value\n+\n+\n class FieldSpec:\n \"\"\"Describes one of the five cron fields.\"\"\"\n \n- def __init__(self, name, minimum, maximum):\n+ def __init__(self, name, minimum, maximum, normalize=None):\n self.name = name\n self.minimum = minimum\n self.maximum = maximum\n+ self.normalize = normalize\n \n def _check(self, value):\n if value < self.minimum or value > self.maximum:\n@@ -23,6 +29,8 @@ class FieldSpec:\n values |= self._parse_part(part)\n if not values:\n raise ValueError(\"empty %s field\" % self.name)\n+ if self.normalize is not None:\n+ values = {self.normalize(value) for value in values}\n return values\n \n def _parse_part(self, part):\n@@ -42,7 +50,7 @@ class FieldSpec:\n start, stop = self._parse_bounds(base)\n else:\n start = self._check(int(base))\n- stop = start\n+ stop = self.maximum\n return set(range(start, stop + 1, step))\n if \"-\" in part:\n start, stop = self._parse_bounds(part)\n@@ -66,7 +74,7 @@ MINUTE = FieldSpec(\"minute\", 0, 59)\n HOUR = FieldSpec(\"hour\", 0, 23)\n DAY_OF_MONTH = FieldSpec(\"day_of_month\", 1, 31)\n MONTH = FieldSpec(\"month\", 1, 12)\n-DAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 6)\n+DAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 7, normalize=_sunday_alias)\n \n \n def parse_field(spec, text):\n", "test_patch": "diff --git a/tests/test_step_and_sunday.py b/tests/test_step_and_sunday.py\nnew file mode 100644\nindex 0000000..7529ebc\n--- /dev/null\n+++ b/tests/test_step_and_sunday.py\n@@ -0,0 +1,43 @@\n+from datetime import datetime\n+\n+from cronlite import CronExpression, next_after\n+from cronlite.fields import DAY_OF_WEEK, MINUTE, parse_field\n+\n+\n+def test_single_value_with_step_runs_to_end_of_range():\n+ assert parse_field(MINUTE, \"5/15\") == {5, 20, 35, 50}\n+\n+\n+def test_single_value_with_step_stops_at_field_maximum():\n+ assert parse_field(MINUTE, \"58/5\") == {58}\n+\n+\n+def test_next_after_with_stepped_start():\n+ expr = CronExpression(\"5/20 * * * *\")\n+ assert next_after(expr, datetime(2026, 3, 4, 0, 6)) == datetime(2026, 3, 4, 0, 25)\n+\n+\n+def test_sunday_may_be_written_as_seven():\n+ assert parse_field(DAY_OF_WEEK, \"7\") == {0}\n+\n+\n+def test_zero_and_seven_are_equivalent():\n+ assert parse_field(DAY_OF_WEEK, \"0\") == parse_field(DAY_OF_WEEK, \"7\")\n+\n+\n+def test_weekend_range_ending_in_seven():\n+ assert parse_field(DAY_OF_WEEK, \"6-7\") == {6, 0}\n+\n+\n+def test_seven_inside_a_list():\n+ assert parse_field(DAY_OF_WEEK, \"1,7\") == {1, 0}\n+\n+\n+def test_next_after_sunday_seven():\n+ expr = CronExpression(\"0 12 * * 7\")\n+ assert next_after(expr, datetime(2026, 3, 4, 0, 0)) == datetime(2026, 3, 8, 12, 0)\n+\n+\n+def test_weekend_range_next_run():\n+ expr = CronExpression(\"0 9 * * 6-7\")\n+ assert next_after(expr, datetime(2026, 3, 6, 0, 0)) == datetime(2026, 3, 7, 9, 0)\n", "problem_statement": "`5/15` in the minute field only fires once an hour, and day-of-week 7 is rejected.\n\nTwo field-parsing bugs, both in `cronlite/fields.py`:\n\n1. A single value followed by a step is treated as a one-element set. `5/15`\n parses to `{5}` instead of `{5, 20, 35, 50}`, so a job scheduled at\n `5/20 * * * *` runs at 00:05, 01:05, 02:05 instead of every twenty minutes\n starting at :05. `*/20` and `1-10/3` are correct -- only the `<value>/<step>`\n form is wrong, because the upper bound collapses to the start value.\n\n2. Sunday cannot be written as 7. `0 12 * * 7` raises\n `ValueError: day_of_week value out of range: 7` at construction time, and so do\n `7`, `1,7` and `6-7`. Standard cron accepts 0-7 for that field with both 0 and 7\n meaning Sunday. The README's \"Day of week\" section asks for the 7 alias to be\n accepted everywhere a value is accepted and collapsed onto 0, so that a parsed\n day-of-week set is always expressed on the 0-6 scale (`6-7` -> `{6, 0}`).\n\nEverything else about the field syntax must keep working, including the existing\nrange checks and the descending-range rejection.", "hints_text": "", "created_at": "2026-10-30", "version": "1.0", "environment_setup_commit": "cb8cd4f111a02d9358774debe834b530bcbfeb94", "FAIL_TO_PASS": "[\"tests/test_step_and_sunday.py::test_next_after_sunday_seven\", \"tests/test_step_and_sunday.py::test_next_after_with_stepped_start\", \"tests/test_step_and_sunday.py::test_seven_inside_a_list\", \"tests/test_step_and_sunday.py::test_single_value_with_step_runs_to_end_of_range\", \"tests/test_step_and_sunday.py::test_sunday_may_be_written_as_seven\", \"tests/test_step_and_sunday.py::test_weekend_range_ending_in_seven\", \"tests/test_step_and_sunday.py::test_weekend_range_next_run\", \"tests/test_step_and_sunday.py::test_zero_and_seven_are_equivalent\"]", "PASS_TO_PASS": "[\"tests/test_basic.py::test_bad_step_rejected\", \"tests/test_basic.py::test_cron_weekday_mapping\", \"tests/test_basic.py::test_descending_range_rejected\", \"tests/test_basic.py::test_invalid_field_count\", \"tests/test_basic.py::test_list_field\", \"tests/test_basic.py::test_list_with_range\", \"tests/test_basic.py::test_matches_every_minute\", \"tests/test_basic.py::test_matches_rejects_wrong_minute\", \"tests/test_basic.py::test_next_after_accepts_string\", \"tests/test_basic.py::test_next_after_basic\", \"tests/test_basic.py::test_next_after_is_strict\", \"tests/test_basic.py::test_next_after_rolls_to_next_day\", \"tests/test_basic.py::test_out_of_range_rejected\", \"tests/test_basic.py::test_range_field\", \"tests/test_basic.py::test_range_step_field\", \"tests/test_basic.py::test_single_value_field\", \"tests/test_basic.py::test_star_field\", \"tests/test_basic.py::test_star_step_field\", \"tests/test_basic.py::test_str_roundtrip\", \"tests/test_basic.py::test_weekday_field_within_zero_to_six\", \"tests/test_step_and_sunday.py::test_single_value_with_step_stops_at_field_maximum\"]", "dockerless": {"language": "python", "python_requires": ">=3.9", "install": [], "run_from": ".", "test_cmd": "python -m pytest -v --tb=no -p no:cacheprovider {tests}", "test_files": ["tests/test_basic.py", "tests/test_step_and_sunday.py"], "files": {"cronlite/__init__.py": "\"\"\"cronlite - a dependency-free five-field cron expression evaluator.\"\"\"\n\nfrom .expr import CronExpression, cron_weekday, next_after\nfrom .fields import (\n DAY_OF_MONTH,\n DAY_OF_WEEK,\n HOUR,\n MINUTE,\n MONTH,\n FieldSpec,\n parse_field,\n)\n\n__version__ = \"0.2.3\"\n\n__all__ = [\n \"CronExpression\",\n \"DAY_OF_MONTH\",\n \"DAY_OF_WEEK\",\n \"FieldSpec\",\n \"HOUR\",\n \"MINUTE\",\n \"MONTH\",\n \"cron_weekday\",\n \"next_after\",\n \"parse_field\",\n]\n", "cronlite/expr.py": "\"\"\"A five-field cron expression evaluator.\"\"\"\n\nfrom datetime import timedelta\n\nfrom .fields import DAY_OF_MONTH, DAY_OF_WEEK, HOUR, MINUTE, MONTH, parse_field\n\nSEARCH_LIMIT_DAYS = 366\n\n\ndef cron_weekday(moment):\n \"\"\"Return the cron weekday of ``moment``: 0 = Sunday, 6 = Saturday.\"\"\"\n return (moment.weekday() + 1) % 7\n\n\nclass CronExpression:\n \"\"\"A parsed ``minute hour day-of-month month day-of-week`` expression.\"\"\"\n\n def __init__(self, expression):\n parts = expression.split()\n if len(parts) != 5:\n raise ValueError(\"expected 5 fields, got %d\" % (len(parts),))\n self.expression = \" \".join(parts)\n self.minutes = parse_field(MINUTE, parts[0])\n self.hours = parse_field(HOUR, parts[1])\n self.days = parse_field(DAY_OF_MONTH, parts[2])\n self.months = parse_field(MONTH, parts[3])\n self.weekdays = parse_field(DAY_OF_WEEK, parts[4])\n\n def matches(self, moment):\n return (\n moment.minute in self.minutes\n and moment.hour in self.hours\n and moment.day in self.days\n and moment.month in self.months\n and cron_weekday(moment) in self.weekdays\n )\n\n def next_after(self, moment):\n \"\"\"Return the first matching minute strictly after ``moment``.\"\"\"\n current = moment.replace(second=0, microsecond=0) + timedelta(minutes=1)\n limit = current + timedelta(days=SEARCH_LIMIT_DAYS)\n while current <= limit:\n if self.matches(current):\n return current\n current += timedelta(minutes=1)\n raise ValueError(\"no matching time within %d days\" % SEARCH_LIMIT_DAYS)\n\n def __str__(self):\n return self.expression\n\n def __repr__(self):\n return \"CronExpression(%r)\" % (self.expression,)\n\n\ndef next_after(expression, moment):\n \"\"\"Convenience wrapper: ``next_after(\"*/5 * * * *\", moment)``.\"\"\"\n if not isinstance(expression, CronExpression):\n expression = CronExpression(expression)\n return expression.next_after(moment)\n", "cronlite/fields.py": "\"\"\"Parsing of individual cron fields into sets of integers.\"\"\"\n\n\nclass FieldSpec:\n \"\"\"Describes one of the five cron fields.\"\"\"\n\n def __init__(self, name, minimum, maximum):\n self.name = name\n self.minimum = minimum\n self.maximum = maximum\n\n def _check(self, value):\n if value < self.minimum or value > self.maximum:\n raise ValueError(\"%s value out of range: %d\" % (self.name, value))\n return value\n\n def parse(self, text):\n values = set()\n for part in text.split(\",\"):\n part = part.strip()\n if not part:\n raise ValueError(\"empty %s component\" % self.name)\n values |= self._parse_part(part)\n if not values:\n raise ValueError(\"empty %s field\" % self.name)\n return values\n\n def _parse_part(self, part):\n if part == \"*\":\n return set(range(self.minimum, self.maximum + 1))\n if \"/\" in part:\n base, _, step_text = part.partition(\"/\")\n try:\n step = int(step_text)\n except ValueError:\n raise ValueError(\"invalid step in %s field: %r\" % (self.name, part))\n if step <= 0:\n raise ValueError(\"step must be positive in %s field\" % self.name)\n if base == \"*\":\n start, stop = self.minimum, self.maximum\n elif \"-\" in base:\n start, stop = self._parse_bounds(base)\n else:\n start = self._check(int(base))\n stop = start\n return set(range(start, stop + 1, step))\n if \"-\" in part:\n start, stop = self._parse_bounds(part)\n return set(range(start, stop + 1))\n return {self._check(int(part))}\n\n def _parse_bounds(self, text):\n low, _, high = text.partition(\"-\")\n try:\n start, stop = int(low), int(high)\n except ValueError:\n raise ValueError(\"invalid range in %s field: %r\" % (self.name, text))\n self._check(start)\n self._check(stop)\n if stop < start:\n raise ValueError(\"descending range in %s field: %r\" % (self.name, text))\n return start, stop\n\n\nMINUTE = FieldSpec(\"minute\", 0, 59)\nHOUR = FieldSpec(\"hour\", 0, 23)\nDAY_OF_MONTH = FieldSpec(\"day_of_month\", 1, 31)\nMONTH = FieldSpec(\"month\", 1, 12)\nDAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 6)\n\n\ndef parse_field(spec, text):\n \"\"\"Parse ``text`` against ``spec`` and return the matching values.\"\"\"\n return spec.parse(text)\n", "README.md": "# cronlite\n\nA dependency-free evaluator for standard five-field cron expressions:\n\n```\nminute hour day-of-month month day-of-week\n```\n\n## Field syntax\n\n| Form | Meaning |\n| --- | --- |\n| `*` | every value in the field range |\n| `7` | a single value |\n| `1-5` | an inclusive range |\n| `*/15` | every 15th value across the whole range |\n| `1-10/3` | every 3rd value inside the range (`1, 4, 7, 10`) |\n| `5/15` | every 15th value starting at 5 and **running to the end of the range** (`5, 20, 35, 50`) |\n| `0,15,30` | a list; any of the above forms may be combined in a list |\n\nField ranges: minute `0-59`, hour `0-23`, day-of-month `1-31`, month `1-12`.\n\n## Day of week\n\nThe day-of-week field is `0-7` where **both `0` and `7` mean Sunday** and\n`1-6` mean Monday to Saturday. `7` must be accepted anywhere a value is\naccepted, including inside ranges such as `6-7` (Saturday and Sunday), and it\nmust behave exactly like `0`. Internally a parsed day-of-week set is expressed\non the `0-6` scale, so `parse_field(DAY_OF_WEEK, \"7\") == {0}` and\n`parse_field(DAY_OF_WEEK, \"6-7\") == {6, 0}`.\n\n## Matching\n\n`CronExpression.matches(moment)` is true when all five fields match. The\nday-of-month and day-of-week fields are combined with AND (not the traditional\nOR). `next_after(moment)` returns the first matching minute strictly after\n`moment`, scanning forward up to 366 days.\n\n## Tests\n\n```\npython -m pytest -q\n```\n", "tests/test_basic.py": "from datetime import datetime\n\nimport pytest\n\nfrom cronlite import CronExpression, cron_weekday, next_after\nfrom cronlite.fields import DAY_OF_WEEK, HOUR, MINUTE, parse_field\n\n\ndef test_star_field():\n assert parse_field(MINUTE, \"*\") == set(range(60))\n\n\ndef test_single_value_field():\n assert parse_field(MINUTE, \"17\") == {17}\n\n\ndef test_list_field():\n assert parse_field(MINUTE, \"0,15,30,45\") == {0, 15, 30, 45}\n\n\ndef test_list_with_range():\n assert parse_field(MINUTE, \"0,10-12\") == {0, 10, 11, 12}\n\n\ndef test_range_field():\n assert parse_field(HOUR, \"9-11\") == {9, 10, 11}\n\n\ndef test_star_step_field():\n assert parse_field(MINUTE, \"*/15\") == {0, 15, 30, 45}\n\n\ndef test_range_step_field():\n assert parse_field(MINUTE, \"1-10/3\") == {1, 4, 7, 10}\n\n\ndef test_out_of_range_rejected():\n with pytest.raises(ValueError):\n parse_field(MINUTE, \"60\")\n with pytest.raises(ValueError):\n parse_field(HOUR, \"24\")\n\n\ndef test_bad_step_rejected():\n with pytest.raises(ValueError):\n parse_field(MINUTE, \"*/0\")\n\n\ndef test_descending_range_rejected():\n with pytest.raises(ValueError):\n parse_field(MINUTE, \"10-1\")\n\n\ndef test_weekday_field_within_zero_to_six():\n assert parse_field(DAY_OF_WEEK, \"1-5\") == {1, 2, 3, 4, 5}\n\n\ndef test_cron_weekday_mapping():\n assert cron_weekday(datetime(2026, 3, 4)) == 3\n assert cron_weekday(datetime(2026, 3, 8)) == 0\n\n\ndef test_matches_every_minute():\n expr = CronExpression(\"* * * * *\")\n assert expr.matches(datetime(2026, 3, 4, 5, 6))\n\n\ndef test_matches_rejects_wrong_minute():\n expr = CronExpression(\"30 9 * * *\")\n assert not expr.matches(datetime(2026, 3, 4, 9, 31))\n\n\ndef test_next_after_basic():\n expr = CronExpression(\"30 9 * * *\")\n assert next_after(expr, datetime(2026, 3, 4, 5, 6)) == datetime(2026, 3, 4, 9, 30)\n\n\ndef test_next_after_is_strict():\n expr = CronExpression(\"30 9 * * *\")\n assert next_after(expr, datetime(2026, 3, 4, 9, 30)) == datetime(2026, 3, 5, 9, 30)\n\n\ndef test_next_after_rolls_to_next_day():\n expr = CronExpression(\"0 0 * * *\")\n assert next_after(expr, datetime(2026, 3, 4, 0, 0)) == datetime(2026, 3, 5, 0, 0)\n\n\ndef test_next_after_accepts_string():\n assert next_after(\"*/30 * * * *\", datetime(2026, 3, 4, 5, 6)) == datetime(2026, 3, 4, 5, 30)\n\n\ndef test_invalid_field_count():\n with pytest.raises(ValueError):\n CronExpression(\"* * * *\")\n\n\ndef test_str_roundtrip():\n assert str(CronExpression(\" 0 12 * * * \")) == \"0 12 * * *\"\n"}}}
4
+ {"instance_id": "swedl__semverlite-1", "repo": "swedl/semverlite", "base_commit": "248819bc3fd540992754e15ab48fcba834ff11d4", "patch": "diff --git a/semverlite/range.py b/semverlite/range.py\nindex abe2ece..ad1fc9e 100644\n--- a/semverlite/range.py\n+++ b/semverlite/range.py\n@@ -40,7 +40,16 @@ class VersionRange:\n raise ValueError(\"empty range\")\n self.clauses = [_parse_clause(part) for part in parts]\n \n+ def _allows_prerelease(self, version):\n+ \"\"\"A prerelease needs an explicit opt-in on the same release triple.\"\"\"\n+ for _, target in self.clauses:\n+ if target.prerelease and target.core == version.core:\n+ return True\n+ return False\n+\n def allows(self, version):\n+ if version.prerelease and not self._allows_prerelease(version):\n+ return False\n return all(self._allows_clause(op, target, version) for op, target in self.clauses)\n \n @staticmethod\ndiff --git a/semverlite/version.py b/semverlite/version.py\nindex bbb779c..4d498ed 100644\n--- a/semverlite/version.py\n+++ b/semverlite/version.py\n@@ -9,6 +9,18 @@ _VERSION_RE = re.compile(\n )\n \n \n+def _identifier_key(identifier):\n+ \"\"\"Sort key for one prerelease identifier.\n+\n+ Numeric identifiers sort numerically and below alphanumeric ones; the third\n+ element keeps keys comparable when the first two tie.\n+ \"\"\"\n+ text = str(identifier)\n+ if text.isdigit():\n+ return (0, int(text), \"\")\n+ return (1, 0, text)\n+\n+\n class Version:\n \"\"\"A semantic version: major.minor.patch[-prerelease][+build].\"\"\"\n \n@@ -43,8 +55,8 @@ class Version:\n \"\"\"Sort key implementing semver precedence (build metadata ignored).\"\"\"\n core = self.core\n if not self.prerelease:\n- return core + (1, ())\n- return core + (0, tuple(str(part) for part in self.prerelease))\n+ return core + ((1,),)\n+ return core + ((0, tuple(_identifier_key(part) for part in self.prerelease)),)\n \n def __str__(self):\n text = \"%d.%d.%d\" % self.core\n", "test_patch": "diff --git a/tests/test_prerelease_precedence.py b/tests/test_prerelease_precedence.py\nnew file mode 100644\nindex 0000000..1ba29fb\n--- /dev/null\n+++ b/tests/test_prerelease_precedence.py\n@@ -0,0 +1,55 @@\n+import pytest\n+\n+from semverlite import Version, VersionRange\n+\n+\n+def v(text):\n+ return Version.parse(text)\n+\n+\n+def test_numeric_identifiers_compare_numerically():\n+ assert v(\"1.0.0-alpha.2\") < v(\"1.0.0-alpha.10\")\n+\n+\n+def test_numeric_identifier_is_lower_than_alphanumeric():\n+ assert v(\"1.0.0-1\") < v(\"1.0.0-alpha\")\n+\n+\n+def test_total_order_matches_semver_precedence():\n+ chain = [\n+ \"1.0.0-alpha\",\n+ \"1.0.0-alpha.1\",\n+ \"1.0.0-alpha.beta\",\n+ \"1.0.0-beta\",\n+ \"1.0.0-beta.2\",\n+ \"1.0.0-beta.11\",\n+ \"1.0.0-rc.1\",\n+ \"1.0.0\",\n+ ]\n+ versions = [v(text) for text in chain]\n+ assert versions == sorted(versions)\n+ assert len(set(versions)) == len(versions)\n+\n+\n+def test_prerelease_does_not_satisfy_release_lower_bound():\n+ assert not VersionRange(\">=1.0.0\").allows(v(\"1.0.1-alpha\"))\n+\n+\n+def test_prerelease_does_not_satisfy_caret_range():\n+ assert not VersionRange(\"^1.2.3\").allows(v(\"1.3.0-beta\"))\n+\n+\n+def test_tilde_range_excludes_prerelease():\n+ assert VersionRange(\"~1.2.3\").allows(v(\"1.2.4\"))\n+ assert not VersionRange(\"~1.2.3\").allows(v(\"1.2.4-rc.1\"))\n+\n+\n+def test_range_allows_prerelease_when_same_triple_is_named():\n+ assert VersionRange(\">=1.0.0-alpha\").allows(v(\"1.0.0-beta\"))\n+ assert not VersionRange(\">=1.0.0-alpha\").allows(v(\"1.0.1-beta\"))\n+\n+\n+def test_prerelease_ordering_is_stable_across_comparisons():\n+ assert v(\"2.0.0-beta.9\") > v(\"2.0.0-beta.8\")\n+ assert v(\"2.0.0-beta.10\") > v(\"2.0.0-beta.9\")\n+ assert not v(\"2.0.0-beta.10\") < v(\"2.0.0-beta.9\")\n", "problem_statement": "Prerelease ordering is lexicographic, and prereleases leak into release ranges.\n\nTwo spec violations against semver 2.0.0:\n\n1. Prerelease identifiers are compared as strings. `1.0.0-alpha.2` sorts *after*\n `1.0.0-alpha.10` because `\"2\" > \"1\"`, and `1.0.0-beta.2` sorts after\n `1.0.0-beta.11`. Sorting a release train produces a wrong order. Numeric\n identifiers must compare numerically, a numeric identifier must sort below an\n alphanumeric one, and a shorter prerelease must sort below a longer one that\n shares its prefix.\n\n2. A prerelease satisfies ranges that never opted into prereleases.\n `VersionRange('>=1.0.0').allows(Version.parse('1.0.1-alpha'))` returns True, and\n so does `~1.2.3` with `1.2.4-rc.1`. That makes our upgrade tool offer release\n candidates as if they were final releases. A prerelease may only satisfy a range\n when some clause names a prerelease on the same `major.minor.patch` triple, so\n `>=1.0.0-alpha` does allow `1.0.0-beta` but not `1.0.1-beta`.\n\n`semverlite/version.py` holds precedence, `semverlite/range.py` holds range\nmatching; `README.md` states both rules precisely. Build metadata must stay\nignored for precedence, and equality/hashing must stay consistent with the new\nordering.", "hints_text": "", "created_at": "2026-10-30", "version": "1.0", "environment_setup_commit": "248819bc3fd540992754e15ab48fcba834ff11d4", "FAIL_TO_PASS": "[\"tests/test_prerelease_precedence.py::test_numeric_identifiers_compare_numerically\", \"tests/test_prerelease_precedence.py::test_prerelease_does_not_satisfy_caret_range\", \"tests/test_prerelease_precedence.py::test_prerelease_does_not_satisfy_release_lower_bound\", \"tests/test_prerelease_precedence.py::test_prerelease_ordering_is_stable_across_comparisons\", \"tests/test_prerelease_precedence.py::test_range_allows_prerelease_when_same_triple_is_named\", \"tests/test_prerelease_precedence.py::test_tilde_range_excludes_prerelease\", \"tests/test_prerelease_precedence.py::test_total_order_matches_semver_precedence\"]", "PASS_TO_PASS": "[\"tests/test_prerelease_precedence.py::test_numeric_identifier_is_lower_than_alphanumeric\", \"tests/test_version.py::test_caret_range\", \"tests/test_version.py::test_equality_and_hash\", \"tests/test_version.py::test_equality_ignores_build_metadata\", \"tests/test_version.py::test_exact_clause\", \"tests/test_version.py::test_inequality\", \"tests/test_version.py::test_invalid_clause_rejected\", \"tests/test_version.py::test_invalid_versions_rejected\", \"tests/test_version.py::test_ordering_by_major\", \"tests/test_version.py::test_ordering_by_minor\", \"tests/test_version.py::test_ordering_by_patch\", \"tests/test_version.py::test_parse_basic\", \"tests/test_version.py::test_parse_prerelease_and_build\", \"tests/test_version.py::test_range_lower_and_upper_bound\", \"tests/test_version.py::test_range_membership_operator\", \"tests/test_version.py::test_release_beats_prerelease\", \"tests/test_version.py::test_shorter_prerelease_is_lower\", \"tests/test_version.py::test_str_roundtrip\", \"tests/test_version.py::test_tilde_range\"]", "dockerless": {"language": "python", "python_requires": ">=3.9", "install": [], "run_from": ".", "test_cmd": "python -m pytest -v --tb=no -p no:cacheprovider {tests}", "test_files": ["tests/test_prerelease_precedence.py", "tests/test_version.py"], "files": {"README.md": "# semverlite\n\nSemantic version parsing, precedence and range matching, following\n[semver 2.0.0](https://semver.org/).\n\n## Precedence\n\n`Version` objects sort by semver precedence:\n\n1. Compare `major`, then `minor`, then `patch` numerically.\n2. A version **with** a prerelease is lower than the same version without one\n (`1.0.0-alpha < 1.0.0`).\n3. Prerelease identifiers are compared left to right. A **numeric** identifier\n always compares numerically, so `1.0.0-alpha.2 < 1.0.0-alpha.10`. An\n alphanumeric identifier compares by ASCII order and is always **greater**\n than a numeric identifier of the same position (`1.0.0-1 < 1.0.0-alpha`).\n A longer prerelease wins when all shared identifiers are equal\n (`1.0.0-alpha < 1.0.0-alpha.1`).\n4. Build metadata is ignored for precedence, so `1.0.0+a == 1.0.0+b`.\n\n## Ranges\n\n`VersionRange(text)` accepts a comma-separated conjunction of clauses using\n`=`, `==`, `>`, `>=`, `<`, `<=`, `^` and `~`. `^1.2.3` means\n`>=1.2.3, <2.0.0`; `~1.2.3` means `>=1.2.3, <1.3.0`.\n\n**Prereleases are excluded from a range unless the range itself opts in.** A\nversion carrying a prerelease satisfies the range only when some clause names a\nprerelease with the *same* `major.minor.patch` triple. So `>=1.0.0` does not\nallow `1.0.1-alpha`, while `>=1.0.0-alpha` does allow `1.0.0-beta`.\n\n## Usage\n\n```python\nfrom semverlite import Version, VersionRange\n\nVersion.parse(\"1.2.3-alpha.1\") < Version.parse(\"1.2.3\")\nVersion.parse(\"1.2.3\") in VersionRange(\">=1.0.0, <2.0.0\")\n```\n\n## Tests\n\n```\npython -m pytest -q\n```\n", "semverlite/__init__.py": "\"\"\"semverlite - semantic version parsing, precedence and ranges.\"\"\"\n\nfrom .range import VersionRange\nfrom .version import Version\n\n__version__ = \"0.5.2\"\n\n__all__ = [\"Version\", \"VersionRange\"]\n", "semverlite/range.py": "\"\"\"Version range expressions such as ``\">=1.2.3, <2.0.0\"``.\"\"\"\n\nimport re\n\nfrom .version import Version\n\n_CLAUSE_RE = re.compile(r\"^(>=|<=|==|=|>|<|\\^|~)?\\s*(\\S+)$\")\n\n\ndef _parse_clause(text):\n match = _CLAUSE_RE.match(text)\n if match is None:\n raise ValueError(\"invalid range clause: %r\" % (text,))\n operator = match.group(1) or \"==\"\n return operator, Version.parse(match.group(2))\n\n\ndef _caret_upper(target):\n \"\"\"Upper bound of ``^target``: the next release that breaks the left-most\n non-zero component.\"\"\"\n if target.major > 0:\n return Version(target.major + 1, 0, 0)\n if target.minor > 0:\n return Version(0, target.minor + 1, 0)\n return Version(0, 0, target.patch + 1)\n\n\ndef _tilde_upper(target):\n \"\"\"Upper bound of ``~target``: the next minor release.\"\"\"\n return Version(target.major, target.minor + 1, 0)\n\n\nclass VersionRange:\n \"\"\"A comma-separated list of clauses that must all hold.\"\"\"\n\n def __init__(self, text):\n self.text = text.strip()\n parts = [part.strip() for part in self.text.split(\",\") if part.strip()]\n if not parts:\n raise ValueError(\"empty range\")\n self.clauses = [_parse_clause(part) for part in parts]\n\n def allows(self, version):\n return all(self._allows_clause(op, target, version) for op, target in self.clauses)\n\n @staticmethod\n def _allows_clause(operator, target, version):\n if operator in (\"=\", \"==\"):\n return version == target\n if operator == \">\":\n return version > target\n if operator == \">=\":\n return version >= target\n if operator == \"<\":\n return version < target\n if operator == \"<=\":\n return version <= target\n if operator == \"^\":\n return target <= version < _caret_upper(target)\n if operator == \"~\":\n return target <= version < _tilde_upper(target)\n raise ValueError(\"unknown operator: %r\" % (operator,))\n\n def __contains__(self, version):\n return self.allows(version)\n\n def __str__(self):\n return self.text\n\n def __repr__(self):\n return \"VersionRange(%r)\" % (self.text,)\n", "semverlite/version.py": "\"\"\"Semantic version parsing and precedence.\"\"\"\n\nimport re\n\n_VERSION_RE = re.compile(\n r\"^(?P<major>0|[1-9]\\d*)\\.(?P<minor>0|[1-9]\\d*)\\.(?P<patch>0|[1-9]\\d*)\"\n r\"(?:-(?P<pre>[0-9A-Za-z.-]+))?\"\n r\"(?:\\+(?P<build>[0-9A-Za-z.-]+))?$\"\n)\n\n\nclass Version:\n \"\"\"A semantic version: major.minor.patch[-prerelease][+build].\"\"\"\n\n def __init__(self, major, minor, patch, prerelease=(), build=()):\n self.major = int(major)\n self.minor = int(minor)\n self.patch = int(patch)\n self.prerelease = tuple(prerelease)\n self.build = tuple(build)\n\n @classmethod\n def parse(cls, text):\n match = _VERSION_RE.match(text.strip())\n if match is None:\n raise ValueError(\"invalid version: %r\" % (text,))\n prerelease = tuple(match.group(\"pre\").split(\".\")) if match.group(\"pre\") else ()\n build = tuple(match.group(\"build\").split(\".\")) if match.group(\"build\") else ()\n return cls(\n match.group(\"major\"),\n match.group(\"minor\"),\n match.group(\"patch\"),\n prerelease,\n build,\n )\n\n @property\n def core(self):\n \"\"\"The (major, minor, patch) triple.\"\"\"\n return (self.major, self.minor, self.patch)\n\n def precedence_key(self):\n \"\"\"Sort key implementing semver precedence (build metadata ignored).\"\"\"\n core = self.core\n if not self.prerelease:\n return core + (1, ())\n return core + (0, tuple(str(part) for part in self.prerelease))\n\n def __str__(self):\n text = \"%d.%d.%d\" % self.core\n if self.prerelease:\n text += \"-\" + \".\".join(str(part) for part in self.prerelease)\n if self.build:\n text += \"+\" + \".\".join(str(part) for part in self.build)\n return text\n\n def __repr__(self):\n return \"Version(%r)\" % (str(self),)\n\n def __eq__(self, other):\n if not isinstance(other, Version):\n return NotImplemented\n return self.precedence_key() == other.precedence_key()\n\n def __ne__(self, other):\n result = self.__eq__(other)\n if result is NotImplemented:\n return result\n return not result\n\n def __lt__(self, other):\n return self.precedence_key() < other.precedence_key()\n\n def __le__(self, other):\n return self.precedence_key() <= other.precedence_key()\n\n def __gt__(self, other):\n return self.precedence_key() > other.precedence_key()\n\n def __ge__(self, other):\n return self.precedence_key() >= other.precedence_key()\n\n def __hash__(self):\n return hash(self.precedence_key())\n", "tests/test_version.py": "import pytest\n\nfrom semverlite import Version, VersionRange\n\n\ndef v(text):\n return Version.parse(text)\n\n\ndef test_parse_basic():\n version = v(\"1.2.3\")\n assert version.major == 1\n assert version.minor == 2\n assert version.patch == 3\n assert version.prerelease == ()\n assert version.build == ()\n\n\ndef test_parse_prerelease_and_build():\n version = v(\"1.2.3-rc.1+build.5\")\n assert version.prerelease == (\"rc\", \"1\")\n assert version.build == (\"build\", \"5\")\n assert version.core == (1, 2, 3)\n\n\ndef test_str_roundtrip():\n for text in (\"0.0.1\", \"1.2.3-alpha\", \"1.2.3-alpha.1+build.5\"):\n assert str(v(text)) == text\n\n\ndef test_invalid_versions_rejected():\n for text in (\"1.2\", \"1.2.3.4\", \"v1.2.3\", \"1.2.x\"):\n with pytest.raises(ValueError):\n Version.parse(text)\n\n\ndef test_ordering_by_patch():\n assert v(\"1.2.3\") < v(\"1.2.4\")\n\n\ndef test_ordering_by_minor():\n assert v(\"1.2.9\") < v(\"1.3.0\")\n\n\ndef test_ordering_by_major():\n assert v(\"1.9.9\") < v(\"2.0.0\")\n\n\ndef test_release_beats_prerelease():\n assert v(\"1.0.0-alpha\") < v(\"1.0.0\")\n assert v(\"1.0.0\") > v(\"1.0.0-rc.9\")\n\n\ndef test_shorter_prerelease_is_lower():\n assert v(\"1.0.0-alpha\") < v(\"1.0.0-alpha.1\")\n\n\ndef test_equality_ignores_build_metadata():\n assert v(\"1.0.0+a\") == v(\"1.0.0+b\")\n assert v(\"1.0.0-alpha+x\") == v(\"1.0.0-alpha+y\")\n\n\ndef test_equality_and_hash():\n assert v(\"1.2.3\") == v(\"1.2.3\")\n assert len({v(\"1.2.3\"), v(\"1.2.3\")}) == 1\n\n\ndef test_inequality():\n assert v(\"1.2.3\") != v(\"1.2.4\")\n\n\ndef test_range_lower_and_upper_bound():\n version_range = VersionRange(\">=1.0.0, <2.0.0\")\n assert version_range.allows(v(\"1.0.0\"))\n assert version_range.allows(v(\"1.5.0\"))\n assert not version_range.allows(v(\"2.0.0\"))\n assert not version_range.allows(v(\"0.9.9\"))\n\n\ndef test_range_membership_operator():\n assert v(\"1.5.0\") in VersionRange(\">=1.0.0, <2.0.0\")\n assert v(\"2.5.0\") not in VersionRange(\">=1.0.0, <2.0.0\")\n\n\ndef test_caret_range():\n version_range = VersionRange(\"^1.2.3\")\n assert version_range.allows(v(\"1.2.3\"))\n assert version_range.allows(v(\"1.9.9\"))\n assert not version_range.allows(v(\"2.0.0\"))\n assert not version_range.allows(v(\"1.2.2\"))\n\n\ndef test_tilde_range():\n version_range = VersionRange(\"~1.2.3\")\n assert version_range.allows(v(\"1.2.9\"))\n assert not version_range.allows(v(\"1.3.0\"))\n\n\ndef test_exact_clause():\n assert VersionRange(\"==1.2.3\").allows(v(\"1.2.3\"))\n assert not VersionRange(\"==1.2.3\").allows(v(\"1.2.4\"))\n\n\ndef test_invalid_clause_rejected():\n with pytest.raises(ValueError):\n VersionRange(\">=nope\")\n"}}}
build_dataset.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build SWE-DockerLess.jsonl from the repos/ fixed/ newtests/ trees.
2
+
3
+ For every instance this script really does the work:
4
+
5
+ 1. git-init the base repo and record the commit sha (base_commit);
6
+ 2. overlay the gold fix, capture ``git diff`` as the patch, restore;
7
+ 3. overlay the new tests, capture ``git diff --cached`` as the test_patch;
8
+ 4. materialise a clean checkout, apply test_patch, run pytest -> "before";
9
+ 5. apply patch, run pytest -> "after";
10
+ 6. derive FAIL_TO_PASS (fail before, pass after) and PASS_TO_PASS
11
+ (pass before, pass after) from the observed outcomes, not from guesses.
12
+
13
+ Run with: python build_dataset.py
14
+ """
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ from pathlib import Path
24
+
25
+ ROOT = Path(__file__).resolve().parent
26
+ REPOS = ROOT / "repos"
27
+ FIXED = ROOT / "fixed"
28
+ NEWTESTS = ROOT / "newtests"
29
+ OUT = ROOT / "SWE-DockerLess.jsonl"
30
+
31
+ STAMP = "2026-10-30T12:00:00+0000"
32
+ GIT_ENV = {
33
+ "GIT_AUTHOR_NAME": "swedl",
34
+ "GIT_AUTHOR_EMAIL": "swedl@example.invalid",
35
+ "GIT_COMMITTER_NAME": "swedl",
36
+ "GIT_COMMITTER_EMAIL": "swedl@example.invalid",
37
+ "GIT_AUTHOR_DATE": STAMP,
38
+ "GIT_COMMITTER_DATE": STAMP,
39
+ "GIT_CONFIG_NOSYSTEM": "1",
40
+ }
41
+ GIT_FLAGS = [
42
+ "-c", "core.autocrlf=false",
43
+ "-c", "core.safecrlf=false",
44
+ "-c", "user.name=swedl",
45
+ "-c", "user.email=swedl@example.invalid",
46
+ "-c", "commit.gpgsign=false",
47
+ ]
48
+
49
+ PYTEST_CMD = "python -m pytest -v --tb=no -p no:cacheprovider"
50
+ RESULT_RE = re.compile(
51
+ r"^(tests/[^\s:]+::[^\s]+)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)"
52
+ )
53
+
54
+ INSTANCES = [
55
+ {
56
+ "instance_id": "swedl__miniconf-1",
57
+ "repo": "swedl/miniconf",
58
+ "name": "miniconf",
59
+ "problem_statement": (
60
+ "Config interpolation blows up on reference cycles and expands escaped text.\n\n"
61
+ "We use miniconf for service configs that are layered from a shared file plus a\n"
62
+ "per-environment overlay. Two problems, both reproducible on main:\n\n"
63
+ "1. A cycle anywhere in the mapping crashes with `RecursionError` instead of the\n"
64
+ " documented error. `Config({'a': '${b}', 'b': '${a}'})['a']` recurses until the\n"
65
+ " interpreter gives up, and the traceback is a thousand frames of `_interpolate`.\n"
66
+ " The README says this must raise `CircularReferenceError` with a message naming\n"
67
+ " the chain, and we rely on that message in our error reporting.\n\n"
68
+ "2. `$$` does not escape. Our TLS config has `cert_subject: \"$${cluster}\"`, meaning\n"
69
+ " the literal text `${cluster}` to be handed to a downstream templating tool, but\n"
70
+ " miniconf substitutes the cluster name into it. The README's escape rule is not\n"
71
+ " implemented at all.\n\n"
72
+ "Both bugs live in `Config._resolve` / `Config._interpolate` in\n"
73
+ "`miniconf/config.py`. `README.md` section \"Interpolation contract\" is the spec we\n"
74
+ "want honoured, including the exact wording of the cycle message and the rule that\n"
75
+ "substituted text is never rescanned for references. A cycle that is unrelated to\n"
76
+ "the key being read must not affect that read, and `as_dict()` must surface cycles\n"
77
+ "like any other read.\n\n"
78
+ "The existing suite passes; the escape and cycle behaviour was never covered."
79
+ ),
80
+ },
81
+ {
82
+ "instance_id": "swedl__ttlcache-1",
83
+ "name": "ttlcache",
84
+ "repo": "swedl/ttlcache",
85
+ "problem_statement": (
86
+ "LRU eviction ignores reads, and len() counts entries that already expired.\n\n"
87
+ "Our request cache is a `TTLCache(maxsize=N, ttl=...)` and it is evicting the wrong\n"
88
+ "keys under load:\n\n"
89
+ "1. Reading a key does not protect it. With `maxsize=2`, writing `a`, `b`, reading\n"
90
+ " `a`, then writing `c` drops `a` and keeps `b` -- the exact opposite of LRU. The\n"
91
+ " same happens when a key is overwritten: the new write keeps the old position\n"
92
+ " instead of becoming the most recently used entry.\n\n"
93
+ "2. `len(cache)` returns the number of stored rows, including rows whose TTL already\n"
94
+ " elapsed. Our metrics dashboard reports a cache that never shrinks even though\n"
95
+ " every read says the key is gone.\n\n"
96
+ "3. `items()` order does not reflect access order for the same reason.\n\n"
97
+ "`README.md` documents the intended contract (sections 2-5): reads and overwrites\n"
98
+ "mark an entry most-recently-used, expired entries are purged before eviction\n"
99
+ "happens, and `len()` counts live entries only. `ttlcache/cache.py` is the file to\n"
100
+ "fix; `ttlcache/clock.py` already gives you a deterministic `FakeClock`.\n\n"
101
+ "Be careful that expiry still deletes the entry on read and that `get()` keeps\n"
102
+ "returning its default for missing keys."
103
+ ),
104
+ },
105
+ {
106
+ "instance_id": "swedl__cronlite-1",
107
+ "name": "cronlite",
108
+ "repo": "swedl/cronlite",
109
+ "problem_statement": (
110
+ "`5/15` in the minute field only fires once an hour, and day-of-week 7 is rejected.\n\n"
111
+ "Two field-parsing bugs, both in `cronlite/fields.py`:\n\n"
112
+ "1. A single value followed by a step is treated as a one-element set. `5/15`\n"
113
+ " parses to `{5}` instead of `{5, 20, 35, 50}`, so a job scheduled at\n"
114
+ " `5/20 * * * *` runs at 00:05, 01:05, 02:05 instead of every twenty minutes\n"
115
+ " starting at :05. `*/20` and `1-10/3` are correct -- only the `<value>/<step>`\n"
116
+ " form is wrong, because the upper bound collapses to the start value.\n\n"
117
+ "2. Sunday cannot be written as 7. `0 12 * * 7` raises\n"
118
+ " `ValueError: day_of_week value out of range: 7` at construction time, and so do\n"
119
+ " `7`, `1,7` and `6-7`. Standard cron accepts 0-7 for that field with both 0 and 7\n"
120
+ " meaning Sunday. The README's \"Day of week\" section asks for the 7 alias to be\n"
121
+ " accepted everywhere a value is accepted and collapsed onto 0, so that a parsed\n"
122
+ " day-of-week set is always expressed on the 0-6 scale (`6-7` -> `{6, 0}`).\n\n"
123
+ "Everything else about the field syntax must keep working, including the existing\n"
124
+ "range checks and the descending-range rejection."
125
+ ),
126
+ },
127
+ {
128
+ "instance_id": "swedl__semverlite-1",
129
+ "name": "semverlite",
130
+ "repo": "swedl/semverlite",
131
+ "problem_statement": (
132
+ "Prerelease ordering is lexicographic, and prereleases leak into release ranges.\n\n"
133
+ "Two spec violations against semver 2.0.0:\n\n"
134
+ "1. Prerelease identifiers are compared as strings. `1.0.0-alpha.2` sorts *after*\n"
135
+ " `1.0.0-alpha.10` because `\"2\" > \"1\"`, and `1.0.0-beta.2` sorts after\n"
136
+ " `1.0.0-beta.11`. Sorting a release train produces a wrong order. Numeric\n"
137
+ " identifiers must compare numerically, a numeric identifier must sort below an\n"
138
+ " alphanumeric one, and a shorter prerelease must sort below a longer one that\n"
139
+ " shares its prefix.\n\n"
140
+ "2. A prerelease satisfies ranges that never opted into prereleases.\n"
141
+ " `VersionRange('>=1.0.0').allows(Version.parse('1.0.1-alpha'))` returns True, and\n"
142
+ " so does `~1.2.3` with `1.2.4-rc.1`. That makes our upgrade tool offer release\n"
143
+ " candidates as if they were final releases. A prerelease may only satisfy a range\n"
144
+ " when some clause names a prerelease on the same `major.minor.patch` triple, so\n"
145
+ " `>=1.0.0-alpha` does allow `1.0.0-beta` but not `1.0.1-beta`.\n\n"
146
+ "`semverlite/version.py` holds precedence, `semverlite/range.py` holds range\n"
147
+ "matching; `README.md` states both rules precisely. Build metadata must stay\n"
148
+ "ignored for precedence, and equality/hashing must stay consistent with the new\n"
149
+ "ordering."
150
+ ),
151
+ },
152
+ ]
153
+
154
+
155
+ def run(cmd, cwd, check=True):
156
+ env = os.environ.copy()
157
+ env.update(GIT_ENV)
158
+ proc = subprocess.run(
159
+ cmd, cwd=str(cwd), capture_output=True, text=True, encoding="utf-8", env=env
160
+ )
161
+ if check and proc.returncode != 0:
162
+ raise RuntimeError(
163
+ "command failed (%d): %s\n--- stdout ---\n%s\n--- stderr ---\n%s"
164
+ % (proc.returncode, " ".join(cmd), proc.stdout, proc.stderr)
165
+ )
166
+ return proc
167
+
168
+
169
+ def git(args, cwd, check=True):
170
+ return run(["git"] + GIT_FLAGS + args, cwd, check=check)
171
+
172
+
173
+ def overlay(src_root, dst_root):
174
+ """Copy every file under src_root into dst_root, preserving relative paths."""
175
+ for path in sorted(src_root.rglob("*")):
176
+ if path.is_dir() or ".git" in path.parts:
177
+ continue
178
+ target = dst_root / path.relative_to(src_root)
179
+ target.parent.mkdir(parents=True, exist_ok=True)
180
+ shutil.copyfile(path, target)
181
+
182
+
183
+ def read_tree(root):
184
+ files = {}
185
+ for path in sorted(root.rglob("*")):
186
+ if path.is_dir() or ".git" in path.parts:
187
+ continue
188
+ rel = path.relative_to(root).as_posix()
189
+ files[rel] = path.read_text(encoding="utf-8")
190
+ return files
191
+
192
+
193
+ def write_tree(files, dest):
194
+ for rel, content in files.items():
195
+ path = dest / rel
196
+ path.parent.mkdir(parents=True, exist_ok=True)
197
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
198
+ handle.write(content)
199
+
200
+
201
+ def parse_outcomes(stdout):
202
+ outcomes = {}
203
+ for raw in stdout.splitlines():
204
+ match = RESULT_RE.match(raw.strip())
205
+ if match:
206
+ outcomes[match.group(1)] = match.group(2)
207
+ return outcomes
208
+
209
+
210
+ def run_tests(dest, test_files):
211
+ proc = run(
212
+ [sys.executable, "-m", "pytest", "-v", "--tb=no", "-p", "no:cacheprovider"]
213
+ + list(test_files),
214
+ dest,
215
+ check=False,
216
+ )
217
+ return parse_outcomes(proc.stdout), proc
218
+
219
+
220
+ def build_instance(spec):
221
+ name = spec["name"]
222
+ repo_dir = REPOS / name
223
+
224
+ git_dir = repo_dir / ".git"
225
+ if git_dir.exists():
226
+ shutil.rmtree(git_dir)
227
+ git(["init", "-q", "-b", "main"], repo_dir)
228
+ git(["add", "-A"], repo_dir)
229
+ git(["commit", "-q", "-m", "initial import"], repo_dir)
230
+ base_commit = git(["rev-parse", "HEAD"], repo_dir).stdout.strip()
231
+
232
+ # --- gold patch -------------------------------------------------------
233
+ overlay(FIXED / name, repo_dir)
234
+ patch = git(["diff", "--no-color", "--no-ext-diff"], repo_dir).stdout
235
+ git(["checkout", "--", "."], repo_dir)
236
+ if not patch.strip():
237
+ raise RuntimeError("%s: gold patch is empty" % name)
238
+
239
+ # --- test patch -------------------------------------------------------
240
+ overlay(NEWTESTS / name, repo_dir)
241
+ git(["add", "-A"], repo_dir)
242
+ test_patch = git(["diff", "--cached", "--no-color", "--no-ext-diff"], repo_dir).stdout
243
+ git(["reset", "-q", "--hard", "HEAD"], repo_dir)
244
+ git(["clean", "-qfd"], repo_dir)
245
+ if not test_patch.strip():
246
+ raise RuntimeError("%s: test patch is empty" % name)
247
+
248
+ base_files = read_tree(repo_dir)
249
+ test_files = sorted(
250
+ rel for rel in base_files if rel.startswith("tests/") and rel.endswith(".py")
251
+ )
252
+ test_files += sorted(
253
+ rel
254
+ for rel in read_tree(NEWTESTS / name)
255
+ if rel.startswith("tests/") and rel.endswith(".py")
256
+ )
257
+ test_files = sorted(set(test_files))
258
+
259
+ # --- verify by really running pytest ----------------------------------
260
+ with tempfile.TemporaryDirectory(prefix="swedl-") as tmp:
261
+ work = Path(tmp) / "work"
262
+ work.mkdir()
263
+ write_tree(base_files, work)
264
+ git(["init", "-q", "-b", "main"], work)
265
+ git(["add", "-A"], work)
266
+ git(["commit", "-q", "-m", "base"], work)
267
+
268
+ test_patch_file = Path(tmp) / "test.patch"
269
+ test_patch_file.write_text(test_patch, encoding="utf-8", newline="\n")
270
+ git(["apply", "--check", str(test_patch_file)], work)
271
+ git(["apply", str(test_patch_file)], work)
272
+
273
+ before, before_proc = run_tests(work, test_files)
274
+
275
+ patch_file = Path(tmp) / "gold.patch"
276
+ patch_file.write_text(patch, encoding="utf-8", newline="\n")
277
+ git(["apply", str(patch_file)], work)
278
+ after, after_proc = run_tests(work, test_files)
279
+
280
+ if not before:
281
+ raise RuntimeError(
282
+ "%s: no test outcomes collected\n%s\n%s"
283
+ % (name, before_proc.stdout[-3000:], before_proc.stderr[-2000:])
284
+ )
285
+ missing = set(before) - set(after)
286
+ if missing:
287
+ raise RuntimeError("%s: tests disappeared after patch: %s" % (name, sorted(missing)))
288
+
289
+ f2p = sorted(
290
+ test
291
+ for test, outcome in before.items()
292
+ if outcome in ("FAILED", "ERROR") and after.get(test) == "PASSED"
293
+ )
294
+ p2p = sorted(
295
+ test
296
+ for test, outcome in before.items()
297
+ if outcome == "PASSED" and after.get(test) == "PASSED"
298
+ )
299
+ broken = sorted(test for test, outcome in after.items() if outcome != "PASSED")
300
+ if broken:
301
+ raise RuntimeError("%s: gold patch leaves failures: %s" % (name, broken))
302
+ if not f2p:
303
+ raise RuntimeError("%s: no FAIL_TO_PASS tests" % name)
304
+ if not p2p:
305
+ raise RuntimeError("%s: no PASS_TO_PASS tests" % name)
306
+
307
+ row = {
308
+ "instance_id": spec["instance_id"],
309
+ "repo": spec["repo"],
310
+ "base_commit": base_commit,
311
+ "patch": patch,
312
+ "test_patch": test_patch,
313
+ "problem_statement": spec["problem_statement"],
314
+ "hints_text": "",
315
+ "created_at": "2026-10-30",
316
+ "version": "1.0",
317
+ "environment_setup_commit": base_commit,
318
+ "FAIL_TO_PASS": json.dumps(f2p),
319
+ "PASS_TO_PASS": json.dumps(p2p),
320
+ "dockerless": {
321
+ "language": "python",
322
+ "python_requires": ">=3.9",
323
+ "install": [],
324
+ "run_from": ".",
325
+ "test_cmd": PYTEST_CMD + " {tests}",
326
+ "test_files": test_files,
327
+ "files": base_files,
328
+ },
329
+ }
330
+ return row, f2p, p2p, len(patch.splitlines())
331
+
332
+
333
+ def main():
334
+ rows = []
335
+ print("%-22s %5s %5s %7s %8s" % ("instance", "F2P", "P2P", "patch", "tests"))
336
+ for spec in INSTANCES:
337
+ row, f2p, p2p, patch_lines = build_instance(spec)
338
+ rows.append(row)
339
+ print(
340
+ "%-22s %5d %5d %7d %8d"
341
+ % (row["instance_id"], len(f2p), len(p2p), patch_lines, len(row["dockerless"]["test_files"]))
342
+ )
343
+ for test in f2p:
344
+ print(" F2P %s" % test)
345
+
346
+ with open(OUT, "w", encoding="utf-8", newline="\n") as handle:
347
+ for row in rows:
348
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
349
+
350
+ size = OUT.stat().st_size
351
+ print("\nwrote %s (%d rows, %.1f KiB)" % (OUT.name, len(rows), size / 1024.0))
352
+
353
+
354
+ if __name__ == "__main__":
355
+ main()
fixed/cronlite/cronlite/fields.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parsing of individual cron fields into sets of integers."""
2
+
3
+
4
+ def _sunday_alias(value):
5
+ """Collapse the cron Sunday alias 7 onto 0."""
6
+ return 0 if value == 7 else value
7
+
8
+
9
+ class FieldSpec:
10
+ """Describes one of the five cron fields."""
11
+
12
+ def __init__(self, name, minimum, maximum, normalize=None):
13
+ self.name = name
14
+ self.minimum = minimum
15
+ self.maximum = maximum
16
+ self.normalize = normalize
17
+
18
+ def _check(self, value):
19
+ if value < self.minimum or value > self.maximum:
20
+ raise ValueError("%s value out of range: %d" % (self.name, value))
21
+ return value
22
+
23
+ def parse(self, text):
24
+ values = set()
25
+ for part in text.split(","):
26
+ part = part.strip()
27
+ if not part:
28
+ raise ValueError("empty %s component" % self.name)
29
+ values |= self._parse_part(part)
30
+ if not values:
31
+ raise ValueError("empty %s field" % self.name)
32
+ if self.normalize is not None:
33
+ values = {self.normalize(value) for value in values}
34
+ return values
35
+
36
+ def _parse_part(self, part):
37
+ if part == "*":
38
+ return set(range(self.minimum, self.maximum + 1))
39
+ if "/" in part:
40
+ base, _, step_text = part.partition("/")
41
+ try:
42
+ step = int(step_text)
43
+ except ValueError:
44
+ raise ValueError("invalid step in %s field: %r" % (self.name, part))
45
+ if step <= 0:
46
+ raise ValueError("step must be positive in %s field" % self.name)
47
+ if base == "*":
48
+ start, stop = self.minimum, self.maximum
49
+ elif "-" in base:
50
+ start, stop = self._parse_bounds(base)
51
+ else:
52
+ start = self._check(int(base))
53
+ stop = self.maximum
54
+ return set(range(start, stop + 1, step))
55
+ if "-" in part:
56
+ start, stop = self._parse_bounds(part)
57
+ return set(range(start, stop + 1))
58
+ return {self._check(int(part))}
59
+
60
+ def _parse_bounds(self, text):
61
+ low, _, high = text.partition("-")
62
+ try:
63
+ start, stop = int(low), int(high)
64
+ except ValueError:
65
+ raise ValueError("invalid range in %s field: %r" % (self.name, text))
66
+ self._check(start)
67
+ self._check(stop)
68
+ if stop < start:
69
+ raise ValueError("descending range in %s field: %r" % (self.name, text))
70
+ return start, stop
71
+
72
+
73
+ MINUTE = FieldSpec("minute", 0, 59)
74
+ HOUR = FieldSpec("hour", 0, 23)
75
+ DAY_OF_MONTH = FieldSpec("day_of_month", 1, 31)
76
+ MONTH = FieldSpec("month", 1, 12)
77
+ DAY_OF_WEEK = FieldSpec("day_of_week", 0, 7, normalize=_sunday_alias)
78
+
79
+
80
+ def parse_field(spec, text):
81
+ """Parse ``text`` against ``spec`` and return the matching values."""
82
+ return spec.parse(text)
fixed/miniconf/miniconf/config.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Config object: layered key/value storage with ${...} interpolation."""
2
+
3
+ from .errors import CircularReferenceError, MissingKeyError
4
+ from .loader import load_layers
5
+
6
+
7
+ class Config:
8
+ """A small configuration mapping whose string values may reference keys.
9
+
10
+ See README.md for the interpolation contract.
11
+ """
12
+
13
+ def __init__(self, data):
14
+ if not isinstance(data, dict):
15
+ raise TypeError("Config data must be a dict")
16
+ self._raw = dict(data)
17
+
18
+ @classmethod
19
+ def from_layers(cls, *layers):
20
+ """Build a Config from one or more dict layers, later layers winning."""
21
+ return cls(load_layers(*layers))
22
+
23
+ def raw(self, key, default=None):
24
+ """Return the unresolved value stored under ``key``."""
25
+ return self._raw.get(key, default)
26
+
27
+ def keys(self):
28
+ return list(self._raw)
29
+
30
+ def get(self, key, default=None):
31
+ if key not in self._raw:
32
+ return default
33
+ return self._resolve(key)
34
+
35
+ def __getitem__(self, key):
36
+ if key not in self._raw:
37
+ raise KeyError(key)
38
+ return self._resolve(key)
39
+
40
+ def __contains__(self, key):
41
+ return key in self._raw
42
+
43
+ def __len__(self):
44
+ return len(self._raw)
45
+
46
+ def as_dict(self):
47
+ """Return every key resolved to a plain value."""
48
+ return {key: self._resolve(key) for key in self._raw}
49
+
50
+ def _resolve(self, key, stack=()):
51
+ if key in stack:
52
+ cycle = stack[stack.index(key):] + (key,)
53
+ raise CircularReferenceError(cycle)
54
+ if key not in self._raw:
55
+ raise MissingKeyError(key, stack[-1] if stack else None)
56
+ value = self._raw[key]
57
+ if not isinstance(value, str):
58
+ return value
59
+ return self._render(value, stack + (key,))
60
+
61
+ def _render(self, text, stack):
62
+ """Resolve references in ``text`` in a single left-to-right pass."""
63
+ out = []
64
+ index = 0
65
+ length = len(text)
66
+ while index < length:
67
+ char = text[index]
68
+ if char != "$":
69
+ out.append(char)
70
+ index += 1
71
+ continue
72
+ if text.startswith("$$", index):
73
+ out.append("$")
74
+ index += 2
75
+ continue
76
+ if text.startswith("${", index):
77
+ end = text.find("}", index + 2)
78
+ if end == -1:
79
+ out.append(char)
80
+ index += 1
81
+ continue
82
+ name = text[index + 2:end]
83
+ if not name:
84
+ out.append(char)
85
+ index += 1
86
+ continue
87
+ out.append(str(self._resolve(name, stack)))
88
+ index = end + 1
89
+ continue
90
+ out.append(char)
91
+ index += 1
92
+ return "".join(out)
fixed/semverlite/semverlite/range.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Version range expressions such as ``">=1.2.3, <2.0.0"``."""
2
+
3
+ import re
4
+
5
+ from .version import Version
6
+
7
+ _CLAUSE_RE = re.compile(r"^(>=|<=|==|=|>|<|\^|~)?\s*(\S+)$")
8
+
9
+
10
+ def _parse_clause(text):
11
+ match = _CLAUSE_RE.match(text)
12
+ if match is None:
13
+ raise ValueError("invalid range clause: %r" % (text,))
14
+ operator = match.group(1) or "=="
15
+ return operator, Version.parse(match.group(2))
16
+
17
+
18
+ def _caret_upper(target):
19
+ """Upper bound of ``^target``: the next release that breaks the left-most
20
+ non-zero component."""
21
+ if target.major > 0:
22
+ return Version(target.major + 1, 0, 0)
23
+ if target.minor > 0:
24
+ return Version(0, target.minor + 1, 0)
25
+ return Version(0, 0, target.patch + 1)
26
+
27
+
28
+ def _tilde_upper(target):
29
+ """Upper bound of ``~target``: the next minor release."""
30
+ return Version(target.major, target.minor + 1, 0)
31
+
32
+
33
+ class VersionRange:
34
+ """A comma-separated list of clauses that must all hold."""
35
+
36
+ def __init__(self, text):
37
+ self.text = text.strip()
38
+ parts = [part.strip() for part in self.text.split(",") if part.strip()]
39
+ if not parts:
40
+ raise ValueError("empty range")
41
+ self.clauses = [_parse_clause(part) for part in parts]
42
+
43
+ def _allows_prerelease(self, version):
44
+ """A prerelease needs an explicit opt-in on the same release triple."""
45
+ for _, target in self.clauses:
46
+ if target.prerelease and target.core == version.core:
47
+ return True
48
+ return False
49
+
50
+ def allows(self, version):
51
+ if version.prerelease and not self._allows_prerelease(version):
52
+ return False
53
+ return all(self._allows_clause(op, target, version) for op, target in self.clauses)
54
+
55
+ @staticmethod
56
+ def _allows_clause(operator, target, version):
57
+ if operator in ("=", "=="):
58
+ return version == target
59
+ if operator == ">":
60
+ return version > target
61
+ if operator == ">=":
62
+ return version >= target
63
+ if operator == "<":
64
+ return version < target
65
+ if operator == "<=":
66
+ return version <= target
67
+ if operator == "^":
68
+ return target <= version < _caret_upper(target)
69
+ if operator == "~":
70
+ return target <= version < _tilde_upper(target)
71
+ raise ValueError("unknown operator: %r" % (operator,))
72
+
73
+ def __contains__(self, version):
74
+ return self.allows(version)
75
+
76
+ def __str__(self):
77
+ return self.text
78
+
79
+ def __repr__(self):
80
+ return "VersionRange(%r)" % (self.text,)
fixed/semverlite/semverlite/version.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Semantic version parsing and precedence."""
2
+
3
+ import re
4
+
5
+ _VERSION_RE = re.compile(
6
+ r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
7
+ r"(?:-(?P<pre>[0-9A-Za-z.-]+))?"
8
+ r"(?:\+(?P<build>[0-9A-Za-z.-]+))?$"
9
+ )
10
+
11
+
12
+ def _identifier_key(identifier):
13
+ """Sort key for one prerelease identifier.
14
+
15
+ Numeric identifiers sort numerically and below alphanumeric ones; the third
16
+ element keeps keys comparable when the first two tie.
17
+ """
18
+ text = str(identifier)
19
+ if text.isdigit():
20
+ return (0, int(text), "")
21
+ return (1, 0, text)
22
+
23
+
24
+ class Version:
25
+ """A semantic version: major.minor.patch[-prerelease][+build]."""
26
+
27
+ def __init__(self, major, minor, patch, prerelease=(), build=()):
28
+ self.major = int(major)
29
+ self.minor = int(minor)
30
+ self.patch = int(patch)
31
+ self.prerelease = tuple(prerelease)
32
+ self.build = tuple(build)
33
+
34
+ @classmethod
35
+ def parse(cls, text):
36
+ match = _VERSION_RE.match(text.strip())
37
+ if match is None:
38
+ raise ValueError("invalid version: %r" % (text,))
39
+ prerelease = tuple(match.group("pre").split(".")) if match.group("pre") else ()
40
+ build = tuple(match.group("build").split(".")) if match.group("build") else ()
41
+ return cls(
42
+ match.group("major"),
43
+ match.group("minor"),
44
+ match.group("patch"),
45
+ prerelease,
46
+ build,
47
+ )
48
+
49
+ @property
50
+ def core(self):
51
+ """The (major, minor, patch) triple."""
52
+ return (self.major, self.minor, self.patch)
53
+
54
+ def precedence_key(self):
55
+ """Sort key implementing semver precedence (build metadata ignored)."""
56
+ core = self.core
57
+ if not self.prerelease:
58
+ return core + ((1,),)
59
+ return core + ((0, tuple(_identifier_key(part) for part in self.prerelease)),)
60
+
61
+ def __str__(self):
62
+ text = "%d.%d.%d" % self.core
63
+ if self.prerelease:
64
+ text += "-" + ".".join(str(part) for part in self.prerelease)
65
+ if self.build:
66
+ text += "+" + ".".join(str(part) for part in self.build)
67
+ return text
68
+
69
+ def __repr__(self):
70
+ return "Version(%r)" % (str(self),)
71
+
72
+ def __eq__(self, other):
73
+ if not isinstance(other, Version):
74
+ return NotImplemented
75
+ return self.precedence_key() == other.precedence_key()
76
+
77
+ def __ne__(self, other):
78
+ result = self.__eq__(other)
79
+ if result is NotImplemented:
80
+ return result
81
+ return not result
82
+
83
+ def __lt__(self, other):
84
+ return self.precedence_key() < other.precedence_key()
85
+
86
+ def __le__(self, other):
87
+ return self.precedence_key() <= other.precedence_key()
88
+
89
+ def __gt__(self, other):
90
+ return self.precedence_key() > other.precedence_key()
91
+
92
+ def __ge__(self, other):
93
+ return self.precedence_key() >= other.precedence_key()
94
+
95
+ def __hash__(self):
96
+ return hash(self.precedence_key())
fixed/ttlcache/ttlcache/cache.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A bounded cache with per-entry time-to-live and LRU eviction."""
2
+
3
+ from collections import OrderedDict
4
+
5
+
6
+ class TTLCache:
7
+ """Fixed-capacity cache where every entry expires ``ttl`` seconds after write.
8
+
9
+ Entries are kept in least-recently-used order. When the cache is full the
10
+ least recently used entry is dropped first. See README.md for the full
11
+ contract.
12
+ """
13
+
14
+ def __init__(self, maxsize=128, ttl=60.0, clock=None):
15
+ if maxsize <= 0:
16
+ raise ValueError("maxsize must be positive")
17
+ if ttl <= 0:
18
+ raise ValueError("ttl must be positive")
19
+ self.maxsize = maxsize
20
+ self.ttl = float(ttl)
21
+ self._clock = clock
22
+ self._data = OrderedDict()
23
+
24
+ def _now(self):
25
+ return self._clock.now() if self._clock is not None else 0.0
26
+
27
+ @staticmethod
28
+ def _expired(deadline, now):
29
+ return now >= deadline
30
+
31
+ def _purge(self, now):
32
+ """Drop every expired entry so it can never be counted or evicted."""
33
+ stale = [key for key, (_, deadline) in self._data.items() if self._expired(deadline, now)]
34
+ for key in stale:
35
+ del self._data[key]
36
+
37
+ def __len__(self):
38
+ now = self._now()
39
+ return sum(1 for _, deadline in self._data.values() if not self._expired(deadline, now))
40
+
41
+ def __contains__(self, key):
42
+ if key not in self._data:
43
+ return False
44
+ _, deadline = self._data[key]
45
+ return not self._expired(deadline, self._now())
46
+
47
+ def __setitem__(self, key, value):
48
+ now = self._now()
49
+ self._purge(now)
50
+ if key in self._data:
51
+ del self._data[key]
52
+ self._data[key] = (value, now + self.ttl)
53
+ while len(self._data) > self.maxsize:
54
+ self._data.popitem(last=False)
55
+
56
+ def __getitem__(self, key):
57
+ value, deadline = self._data[key]
58
+ if self._expired(deadline, self._now()):
59
+ del self._data[key]
60
+ raise KeyError(key)
61
+ self._data.move_to_end(key)
62
+ return value
63
+
64
+ def get(self, key, default=None):
65
+ try:
66
+ return self[key]
67
+ except KeyError:
68
+ return default
69
+
70
+ def setdefault(self, key, factory):
71
+ """Return the live value for ``key``, computing and storing it if absent."""
72
+ if key in self:
73
+ return self[key]
74
+ value = factory()
75
+ self[key] = value
76
+ return value
77
+
78
+ def pop(self, key, default=None):
79
+ if key not in self._data:
80
+ return default
81
+ value, _ = self._data.pop(key)
82
+ return value
83
+
84
+ def items(self):
85
+ """Iterate over live ``(key, value)`` pairs in LRU order."""
86
+ now = self._now()
87
+ return [(k, v) for k, (v, d) in self._data.items() if not self._expired(d, now)]
88
+
89
+ def __repr__(self):
90
+ return "TTLCache(maxsize=%d, ttl=%r, live=%d)" % (
91
+ self.maxsize,
92
+ self.ttl,
93
+ len(self),
94
+ )
newtests/cronlite/tests/test_step_and_sunday.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from cronlite import CronExpression, next_after
4
+ from cronlite.fields import DAY_OF_WEEK, MINUTE, parse_field
5
+
6
+
7
+ def test_single_value_with_step_runs_to_end_of_range():
8
+ assert parse_field(MINUTE, "5/15") == {5, 20, 35, 50}
9
+
10
+
11
+ def test_single_value_with_step_stops_at_field_maximum():
12
+ assert parse_field(MINUTE, "58/5") == {58}
13
+
14
+
15
+ def test_next_after_with_stepped_start():
16
+ expr = CronExpression("5/20 * * * *")
17
+ assert next_after(expr, datetime(2026, 3, 4, 0, 6)) == datetime(2026, 3, 4, 0, 25)
18
+
19
+
20
+ def test_sunday_may_be_written_as_seven():
21
+ assert parse_field(DAY_OF_WEEK, "7") == {0}
22
+
23
+
24
+ def test_zero_and_seven_are_equivalent():
25
+ assert parse_field(DAY_OF_WEEK, "0") == parse_field(DAY_OF_WEEK, "7")
26
+
27
+
28
+ def test_weekend_range_ending_in_seven():
29
+ assert parse_field(DAY_OF_WEEK, "6-7") == {6, 0}
30
+
31
+
32
+ def test_seven_inside_a_list():
33
+ assert parse_field(DAY_OF_WEEK, "1,7") == {1, 0}
34
+
35
+
36
+ def test_next_after_sunday_seven():
37
+ expr = CronExpression("0 12 * * 7")
38
+ assert next_after(expr, datetime(2026, 3, 4, 0, 0)) == datetime(2026, 3, 8, 12, 0)
39
+
40
+
41
+ def test_weekend_range_next_run():
42
+ expr = CronExpression("0 9 * * 6-7")
43
+ assert next_after(expr, datetime(2026, 3, 6, 0, 0)) == datetime(2026, 3, 7, 9, 0)
newtests/miniconf/tests/test_interpolation_edge_cases.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from miniconf import CircularReferenceError, Config, MissingKeyError
4
+
5
+
6
+ def test_dollar_escape():
7
+ cfg = Config({"price": "$${amount}"})
8
+ assert cfg["price"] == "${amount}"
9
+
10
+
11
+ def test_escape_next_to_reference():
12
+ cfg = Config({"name": "wren", "msg": "$${name} is ${name}"})
13
+ assert cfg["msg"] == "${name} is wren"
14
+
15
+
16
+ def test_self_reference():
17
+ cfg = Config({"a": "x${a}"})
18
+ with pytest.raises(CircularReferenceError):
19
+ cfg["a"]
20
+
21
+
22
+ def test_as_dict_raises_on_cycle():
23
+ cfg = Config({"a": "${b}", "b": "${a}"})
24
+ with pytest.raises(CircularReferenceError):
25
+ cfg.as_dict()
26
+
27
+
28
+ def test_cycle_not_involving_requested_key():
29
+ cfg = Config({"a": "fine", "b": "${c}", "c": "${b}"})
30
+ assert cfg["a"] == "fine"
31
+ with pytest.raises(CircularReferenceError):
32
+ cfg["b"]
33
+
34
+
35
+ def test_two_cycle_chain_starts_at_requested_key():
36
+ cfg = Config({"a": "${b}", "b": "${a}"})
37
+ with pytest.raises(CircularReferenceError) as excinfo:
38
+ cfg["a"]
39
+ assert str(excinfo.value) == "circular reference: a -> b -> a"
40
+
41
+
42
+ def test_self_reference_message():
43
+ cfg = Config({"loop": "${loop}"})
44
+ with pytest.raises(CircularReferenceError) as excinfo:
45
+ cfg["loop"]
46
+ assert str(excinfo.value) == "circular reference: loop -> loop"
47
+
48
+
49
+ def test_escaped_text_is_not_reinterpolated_through_a_reference():
50
+ cfg = Config({"inner": "$${leak}", "outer": "${inner}"})
51
+ assert cfg["outer"] == "${leak}"
52
+
53
+
54
+ def test_missing_key_inside_reference_chain():
55
+ cfg = Config({"a": "${b}", "b": "${nope}"})
56
+ with pytest.raises(MissingKeyError) as excinfo:
57
+ cfg["a"]
58
+ assert str(excinfo.value) == "missing key 'nope' referenced from 'b'"
59
+
60
+
61
+ def test_escape_does_not_hide_a_real_cycle():
62
+ cfg = Config({"a": "$${b}", "b": "${a}"})
63
+ assert cfg["a"] == "${b}"
64
+ assert cfg["b"] == "${b}"
newtests/semverlite/tests/test_prerelease_precedence.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from semverlite import Version, VersionRange
4
+
5
+
6
+ def v(text):
7
+ return Version.parse(text)
8
+
9
+
10
+ def test_numeric_identifiers_compare_numerically():
11
+ assert v("1.0.0-alpha.2") < v("1.0.0-alpha.10")
12
+
13
+
14
+ def test_numeric_identifier_is_lower_than_alphanumeric():
15
+ assert v("1.0.0-1") < v("1.0.0-alpha")
16
+
17
+
18
+ def test_total_order_matches_semver_precedence():
19
+ chain = [
20
+ "1.0.0-alpha",
21
+ "1.0.0-alpha.1",
22
+ "1.0.0-alpha.beta",
23
+ "1.0.0-beta",
24
+ "1.0.0-beta.2",
25
+ "1.0.0-beta.11",
26
+ "1.0.0-rc.1",
27
+ "1.0.0",
28
+ ]
29
+ versions = [v(text) for text in chain]
30
+ assert versions == sorted(versions)
31
+ assert len(set(versions)) == len(versions)
32
+
33
+
34
+ def test_prerelease_does_not_satisfy_release_lower_bound():
35
+ assert not VersionRange(">=1.0.0").allows(v("1.0.1-alpha"))
36
+
37
+
38
+ def test_prerelease_does_not_satisfy_caret_range():
39
+ assert not VersionRange("^1.2.3").allows(v("1.3.0-beta"))
40
+
41
+
42
+ def test_tilde_range_excludes_prerelease():
43
+ assert VersionRange("~1.2.3").allows(v("1.2.4"))
44
+ assert not VersionRange("~1.2.3").allows(v("1.2.4-rc.1"))
45
+
46
+
47
+ def test_range_allows_prerelease_when_same_triple_is_named():
48
+ assert VersionRange(">=1.0.0-alpha").allows(v("1.0.0-beta"))
49
+ assert not VersionRange(">=1.0.0-alpha").allows(v("1.0.1-beta"))
50
+
51
+
52
+ def test_prerelease_ordering_is_stable_across_comparisons():
53
+ assert v("2.0.0-beta.9") > v("2.0.0-beta.8")
54
+ assert v("2.0.0-beta.10") > v("2.0.0-beta.9")
55
+ assert not v("2.0.0-beta.10") < v("2.0.0-beta.9")
newtests/ttlcache/tests/test_lru_semantics.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ttlcache import FakeClock, TTLCache
2
+
3
+
4
+ def test_get_refreshes_recency():
5
+ clock = FakeClock()
6
+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)
7
+ cache["a"] = 1
8
+ cache["b"] = 2
9
+ assert cache["a"] == 1
10
+ cache["c"] = 3
11
+ assert "a" in cache
12
+ assert "b" not in cache
13
+
14
+
15
+ def test_overwrite_refreshes_recency():
16
+ clock = FakeClock()
17
+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)
18
+ cache["a"] = 1
19
+ cache["b"] = 2
20
+ cache["a"] = 9
21
+ cache["c"] = 3
22
+ assert cache["a"] == 9
23
+ assert "b" not in cache
24
+
25
+
26
+ def test_setdefault_refreshes_recency():
27
+ clock = FakeClock()
28
+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)
29
+ cache["a"] = 1
30
+ cache["b"] = 2
31
+ assert cache.setdefault("a", lambda: 99) == 1
32
+ cache["c"] = 3
33
+ assert "a" in cache
34
+ assert "b" not in cache
35
+
36
+
37
+ def test_len_ignores_expired_entries():
38
+ clock = FakeClock()
39
+ cache = TTLCache(maxsize=4, ttl=10.0, clock=clock)
40
+ cache["a"] = 1
41
+ clock.advance(5)
42
+ cache["b"] = 2
43
+ clock.advance(6)
44
+ assert len(cache) == 1
45
+ assert "a" not in cache
46
+ assert "b" in cache
47
+
48
+
49
+ def test_items_reports_least_recently_used_first():
50
+ clock = FakeClock()
51
+ cache = TTLCache(maxsize=3, ttl=10.0, clock=clock)
52
+ cache["a"] = 1
53
+ cache["b"] = 2
54
+ assert cache["a"] == 1
55
+ assert list(cache.items()) == [("b", 2), ("a", 1)]
predictions/cross.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"instance_id": "swedl__miniconf-1", "model_name_or_path": "control-cross", "model_patch": "diff --git a/ttlcache/cache.py b/ttlcache/cache.py\nindex fda1724..4c36ad4 100644\n--- a/ttlcache/cache.py\n+++ b/ttlcache/cache.py\n@@ -28,8 +28,15 @@ class TTLCache:\n def _expired(deadline, now):\n return now >= deadline\n \n+ def _purge(self, now):\n+ \"\"\"Drop every expired entry so it can never be counted or evicted.\"\"\"\n+ stale = [key for key, (_, deadline) in self._data.items() if self._expired(deadline, now)]\n+ for key in stale:\n+ del self._data[key]\n+\n def __len__(self):\n- return len(self._data)\n+ now = self._now()\n+ return sum(1 for _, deadline in self._data.values() if not self._expired(deadline, now))\n \n def __contains__(self, key):\n if key not in self._data:\n@@ -39,6 +46,9 @@ class TTLCache:\n \n def __setitem__(self, key, value):\n now = self._now()\n+ self._purge(now)\n+ if key in self._data:\n+ del self._data[key]\n self._data[key] = (value, now + self.ttl)\n while len(self._data) > self.maxsize:\n self._data.popitem(last=False)\n@@ -48,6 +58,7 @@ class TTLCache:\n if self._expired(deadline, self._now()):\n del self._data[key]\n raise KeyError(key)\n+ self._data.move_to_end(key)\n return value\n \n def get(self, key, default=None):\n"}
2
+ {"instance_id": "swedl__ttlcache-1", "model_name_or_path": "control-cross", "model_patch": "diff --git a/cronlite/fields.py b/cronlite/fields.py\nindex 4945d5e..b3c0eb6 100644\n--- a/cronlite/fields.py\n+++ b/cronlite/fields.py\n@@ -1,13 +1,19 @@\n \"\"\"Parsing of individual cron fields into sets of integers.\"\"\"\n \n \n+def _sunday_alias(value):\n+ \"\"\"Collapse the cron Sunday alias 7 onto 0.\"\"\"\n+ return 0 if value == 7 else value\n+\n+\n class FieldSpec:\n \"\"\"Describes one of the five cron fields.\"\"\"\n \n- def __init__(self, name, minimum, maximum):\n+ def __init__(self, name, minimum, maximum, normalize=None):\n self.name = name\n self.minimum = minimum\n self.maximum = maximum\n+ self.normalize = normalize\n \n def _check(self, value):\n if value < self.minimum or value > self.maximum:\n@@ -23,6 +29,8 @@ class FieldSpec:\n values |= self._parse_part(part)\n if not values:\n raise ValueError(\"empty %s field\" % self.name)\n+ if self.normalize is not None:\n+ values = {self.normalize(value) for value in values}\n return values\n \n def _parse_part(self, part):\n@@ -42,7 +50,7 @@ class FieldSpec:\n start, stop = self._parse_bounds(base)\n else:\n start = self._check(int(base))\n- stop = start\n+ stop = self.maximum\n return set(range(start, stop + 1, step))\n if \"-\" in part:\n start, stop = self._parse_bounds(part)\n@@ -66,7 +74,7 @@ MINUTE = FieldSpec(\"minute\", 0, 59)\n HOUR = FieldSpec(\"hour\", 0, 23)\n DAY_OF_MONTH = FieldSpec(\"day_of_month\", 1, 31)\n MONTH = FieldSpec(\"month\", 1, 12)\n-DAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 6)\n+DAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 7, normalize=_sunday_alias)\n \n \n def parse_field(spec, text):\n"}
3
+ {"instance_id": "swedl__cronlite-1", "model_name_or_path": "control-cross", "model_patch": "diff --git a/semverlite/range.py b/semverlite/range.py\nindex abe2ece..ad1fc9e 100644\n--- a/semverlite/range.py\n+++ b/semverlite/range.py\n@@ -40,7 +40,16 @@ class VersionRange:\n raise ValueError(\"empty range\")\n self.clauses = [_parse_clause(part) for part in parts]\n \n+ def _allows_prerelease(self, version):\n+ \"\"\"A prerelease needs an explicit opt-in on the same release triple.\"\"\"\n+ for _, target in self.clauses:\n+ if target.prerelease and target.core == version.core:\n+ return True\n+ return False\n+\n def allows(self, version):\n+ if version.prerelease and not self._allows_prerelease(version):\n+ return False\n return all(self._allows_clause(op, target, version) for op, target in self.clauses)\n \n @staticmethod\ndiff --git a/semverlite/version.py b/semverlite/version.py\nindex bbb779c..4d498ed 100644\n--- a/semverlite/version.py\n+++ b/semverlite/version.py\n@@ -9,6 +9,18 @@ _VERSION_RE = re.compile(\n )\n \n \n+def _identifier_key(identifier):\n+ \"\"\"Sort key for one prerelease identifier.\n+\n+ Numeric identifiers sort numerically and below alphanumeric ones; the third\n+ element keeps keys comparable when the first two tie.\n+ \"\"\"\n+ text = str(identifier)\n+ if text.isdigit():\n+ return (0, int(text), \"\")\n+ return (1, 0, text)\n+\n+\n class Version:\n \"\"\"A semantic version: major.minor.patch[-prerelease][+build].\"\"\"\n \n@@ -43,8 +55,8 @@ class Version:\n \"\"\"Sort key implementing semver precedence (build metadata ignored).\"\"\"\n core = self.core\n if not self.prerelease:\n- return core + (1, ())\n- return core + (0, tuple(str(part) for part in self.prerelease))\n+ return core + ((1,),)\n+ return core + ((0, tuple(_identifier_key(part) for part in self.prerelease)),)\n \n def __str__(self):\n text = \"%d.%d.%d\" % self.core\n"}
4
+ {"instance_id": "swedl__semverlite-1", "model_name_or_path": "control-cross", "model_patch": "diff --git a/miniconf/config.py b/miniconf/config.py\nindex 8751912..6bdf695 100644\n--- a/miniconf/config.py\n+++ b/miniconf/config.py\n@@ -1,12 +1,8 @@\n \"\"\"The Config object: layered key/value storage with ${...} interpolation.\"\"\"\n \n-import re\n-\n-from .errors import MissingKeyError\n+from .errors import CircularReferenceError, MissingKeyError\n from .loader import load_layers\n \n-REFERENCE = re.compile(r\"\\$\\{([A-Za-z_][A-Za-z0-9_.-]*)\\}\")\n-\n \n class Config:\n \"\"\"A small configuration mapping whose string values may reference keys.\n@@ -51,17 +47,46 @@ class Config:\n \"\"\"Return every key resolved to a plain value.\"\"\"\n return {key: self._resolve(key) for key in self._raw}\n \n- def _resolve(self, key):\n+ def _resolve(self, key, stack=()):\n+ if key in stack:\n+ cycle = stack[stack.index(key):] + (key,)\n+ raise CircularReferenceError(cycle)\n+ if key not in self._raw:\n+ raise MissingKeyError(key, stack[-1] if stack else None)\n value = self._raw[key]\n if not isinstance(value, str):\n return value\n- return self._interpolate(value, key)\n-\n- def _interpolate(self, text, origin):\n- def replace(match):\n- name = match.group(1)\n- if name not in self._raw:\n- raise MissingKeyError(name, origin)\n- return str(self._resolve(name))\n-\n- return REFERENCE.sub(replace, text)\n+ return self._render(value, stack + (key,))\n+\n+ def _render(self, text, stack):\n+ \"\"\"Resolve references in ``text`` in a single left-to-right pass.\"\"\"\n+ out = []\n+ index = 0\n+ length = len(text)\n+ while index < length:\n+ char = text[index]\n+ if char != \"$\":\n+ out.append(char)\n+ index += 1\n+ continue\n+ if text.startswith(\"$$\", index):\n+ out.append(\"$\")\n+ index += 2\n+ continue\n+ if text.startswith(\"${\", index):\n+ end = text.find(\"}\", index + 2)\n+ if end == -1:\n+ out.append(char)\n+ index += 1\n+ continue\n+ name = text[index + 2:end]\n+ if not name:\n+ out.append(char)\n+ index += 1\n+ continue\n+ out.append(str(self._resolve(name, stack)))\n+ index = end + 1\n+ continue\n+ out.append(char)\n+ index += 1\n+ return \"\".join(out)\n"}
predictions/empty.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"instance_id": "swedl__miniconf-1", "model_name_or_path": "control-empty", "model_patch": ""}
2
+ {"instance_id": "swedl__ttlcache-1", "model_name_or_path": "control-empty", "model_patch": ""}
3
+ {"instance_id": "swedl__cronlite-1", "model_name_or_path": "control-empty", "model_patch": ""}
4
+ {"instance_id": "swedl__semverlite-1", "model_name_or_path": "control-empty", "model_patch": ""}
predictions/partial.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"instance_id": "swedl__miniconf-1", "model_name_or_path": "control-partial", "model_patch": "diff --git a/miniconf/config.py b/miniconf/config.py\nindex 8751912..952e616 100644\n--- a/miniconf/config.py\n+++ b/miniconf/config.py\n@@ -1,12 +1,8 @@\n \"\"\"The Config object: layered key/value storage with ${...} interpolation.\"\"\"\n \n-import re\n-\n-from .errors import MissingKeyError\n+from .errors import CircularReferenceError, MissingKeyError\n from .loader import load_layers\n \n-REFERENCE = re.compile(r\"\\$\\{([A-Za-z_][A-Za-z0-9_.-]*)\\}\")\n-\n \n class Config:\n \"\"\"A small configuration mapping whose string values may reference keys.\n@@ -51,17 +47,42 @@ class Config:\n \"\"\"Return every key resolved to a plain value.\"\"\"\n return {key: self._resolve(key) for key in self._raw}\n \n- def _resolve(self, key):\n+ def _resolve(self, key, stack=()):\n+ if key in stack:\n+ cycle = stack[stack.index(key):] + (key,)\n+ raise CircularReferenceError(cycle)\n+ if key not in self._raw:\n+ raise MissingKeyError(key, stack[-1] if stack else None)\n value = self._raw[key]\n if not isinstance(value, str):\n return value\n- return self._interpolate(value, key)\n-\n- def _interpolate(self, text, origin):\n- def replace(match):\n- name = match.group(1)\n- if name not in self._raw:\n- raise MissingKeyError(name, origin)\n- return str(self._resolve(name))\n-\n- return REFERENCE.sub(replace, text)\n+ return self._render(value, stack + (key,))\n+\n+ def _render(self, text, stack):\n+ \"\"\"Resolve references in ``text`` in a single left-to-right pass.\"\"\"\n+ out = []\n+ index = 0\n+ length = len(text)\n+ while index < length:\n+ char = text[index]\n+ if char != \"$\":\n+ out.append(char)\n+ index += 1\n+ continue\n+ if text.startswith(\"${\", index):\n+ end = text.find(\"}\", index + 2)\n+ if end == -1:\n+ out.append(char)\n+ index += 1\n+ continue\n+ name = text[index + 2:end]\n+ if not name:\n+ out.append(char)\n+ index += 1\n+ continue\n+ out.append(str(self._resolve(name, stack)))\n+ index = end + 1\n+ continue\n+ out.append(char)\n+ index += 1\n+ return \"\".join(out)\n"}
2
+ {"instance_id": "swedl__ttlcache-1", "model_name_or_path": "control-partial", "model_patch": "diff --git a/ttlcache/cache.py b/ttlcache/cache.py\nindex fda1724..4088655 100644\n--- a/ttlcache/cache.py\n+++ b/ttlcache/cache.py\n@@ -28,8 +28,15 @@ class TTLCache:\n def _expired(deadline, now):\n return now >= deadline\n \n+ def _purge(self, now):\n+ \"\"\"Drop every expired entry so it can never be counted or evicted.\"\"\"\n+ stale = [key for key, (_, deadline) in self._data.items() if self._expired(deadline, now)]\n+ for key in stale:\n+ del self._data[key]\n+\n def __len__(self):\n- return len(self._data)\n+ now = self._now()\n+ return sum(1 for _, deadline in self._data.values() if not self._expired(deadline, now))\n \n def __contains__(self, key):\n if key not in self._data:\n@@ -39,6 +46,9 @@ class TTLCache:\n \n def __setitem__(self, key, value):\n now = self._now()\n+ self._purge(now)\n+ if key in self._data:\n+ del self._data[key]\n self._data[key] = (value, now + self.ttl)\n while len(self._data) > self.maxsize:\n self._data.popitem(last=False)\n"}
3
+ {"instance_id": "swedl__cronlite-1", "model_name_or_path": "control-partial", "model_patch": "diff --git a/cronlite/fields.py b/cronlite/fields.py\nindex 4945d5e..6af09a9 100644\n--- a/cronlite/fields.py\n+++ b/cronlite/fields.py\n@@ -1,13 +1,19 @@\n \"\"\"Parsing of individual cron fields into sets of integers.\"\"\"\n \n \n+def _sunday_alias(value):\n+ \"\"\"Collapse the cron Sunday alias 7 onto 0.\"\"\"\n+ return 0 if value == 7 else value\n+\n+\n class FieldSpec:\n \"\"\"Describes one of the five cron fields.\"\"\"\n \n- def __init__(self, name, minimum, maximum):\n+ def __init__(self, name, minimum, maximum, normalize=None):\n self.name = name\n self.minimum = minimum\n self.maximum = maximum\n+ self.normalize = normalize\n \n def _check(self, value):\n if value < self.minimum or value > self.maximum:\n@@ -23,6 +29,8 @@ class FieldSpec:\n values |= self._parse_part(part)\n if not values:\n raise ValueError(\"empty %s field\" % self.name)\n+ if self.normalize is not None:\n+ values = {self.normalize(value) for value in values}\n return values\n \n def _parse_part(self, part):\n@@ -66,7 +74,7 @@ MINUTE = FieldSpec(\"minute\", 0, 59)\n HOUR = FieldSpec(\"hour\", 0, 23)\n DAY_OF_MONTH = FieldSpec(\"day_of_month\", 1, 31)\n MONTH = FieldSpec(\"month\", 1, 12)\n-DAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 6)\n+DAY_OF_WEEK = FieldSpec(\"day_of_week\", 0, 7, normalize=_sunday_alias)\n \n \n def parse_field(spec, text):\n"}
4
+ {"instance_id": "swedl__semverlite-1", "model_name_or_path": "control-partial", "model_patch": "diff --git a/semverlite/version.py b/semverlite/version.py\nindex bbb779c..4d498ed 100644\n--- a/semverlite/version.py\n+++ b/semverlite/version.py\n@@ -9,6 +9,18 @@ _VERSION_RE = re.compile(\n )\n \n \n+def _identifier_key(identifier):\n+ \"\"\"Sort key for one prerelease identifier.\n+\n+ Numeric identifiers sort numerically and below alphanumeric ones; the third\n+ element keeps keys comparable when the first two tie.\n+ \"\"\"\n+ text = str(identifier)\n+ if text.isdigit():\n+ return (0, int(text), \"\")\n+ return (1, 0, text)\n+\n+\n class Version:\n \"\"\"A semantic version: major.minor.patch[-prerelease][+build].\"\"\"\n \n@@ -43,8 +55,8 @@ class Version:\n \"\"\"Sort key implementing semver precedence (build metadata ignored).\"\"\"\n core = self.core\n if not self.prerelease:\n- return core + (1, ())\n- return core + (0, tuple(str(part) for part in self.prerelease))\n+ return core + ((1,),)\n+ return core + ((0, tuple(_identifier_key(part) for part in self.prerelease)),)\n \n def __str__(self):\n text = \"%d.%d.%d\" % self.core\n"}
reports/cross.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "SWE-DockerLess.jsonl",
3
+ "instances": 4,
4
+ "resolved": 0,
5
+ "resolve_rate": 0.0,
6
+ "seconds": 2.58,
7
+ "results": [
8
+ {
9
+ "instance_id": "swedl__miniconf-1",
10
+ "resolved": false,
11
+ "reason": "model patch failed to apply: ['error: ttlcache/cache.py: No such file or directory']",
12
+ "f2p_passed": 0,
13
+ "f2p_total": 9,
14
+ "p2p_passed": 0,
15
+ "p2p_total": 15
16
+ },
17
+ {
18
+ "instance_id": "swedl__ttlcache-1",
19
+ "resolved": false,
20
+ "reason": "model patch failed to apply: ['error: cronlite/fields.py: No such file or directory']",
21
+ "f2p_passed": 0,
22
+ "f2p_total": 5,
23
+ "p2p_passed": 0,
24
+ "p2p_total": 12
25
+ },
26
+ {
27
+ "instance_id": "swedl__cronlite-1",
28
+ "resolved": false,
29
+ "reason": "model patch failed to apply: ['error: semverlite/range.py: No such file or directory', 'error: semverlite/version.py: No such file or directory']",
30
+ "f2p_passed": 0,
31
+ "f2p_total": 8,
32
+ "p2p_passed": 0,
33
+ "p2p_total": 21
34
+ },
35
+ {
36
+ "instance_id": "swedl__semverlite-1",
37
+ "resolved": false,
38
+ "reason": "model patch failed to apply: ['error: miniconf/config.py: No such file or directory']",
39
+ "f2p_passed": 0,
40
+ "f2p_total": 7,
41
+ "p2p_passed": 0,
42
+ "p2p_total": 19
43
+ }
44
+ ]
45
+ }
reports/empty.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "SWE-DockerLess.jsonl",
3
+ "instances": 4,
4
+ "resolved": 0,
5
+ "resolve_rate": 0.0,
6
+ "seconds": 2.49,
7
+ "results": [
8
+ {
9
+ "instance_id": "swedl__miniconf-1",
10
+ "resolved": false,
11
+ "reason": "model patch failed to apply: empty patch",
12
+ "f2p_passed": 0,
13
+ "f2p_total": 9,
14
+ "p2p_passed": 0,
15
+ "p2p_total": 15
16
+ },
17
+ {
18
+ "instance_id": "swedl__ttlcache-1",
19
+ "resolved": false,
20
+ "reason": "model patch failed to apply: empty patch",
21
+ "f2p_passed": 0,
22
+ "f2p_total": 5,
23
+ "p2p_passed": 0,
24
+ "p2p_total": 12
25
+ },
26
+ {
27
+ "instance_id": "swedl__cronlite-1",
28
+ "resolved": false,
29
+ "reason": "model patch failed to apply: empty patch",
30
+ "f2p_passed": 0,
31
+ "f2p_total": 8,
32
+ "p2p_passed": 0,
33
+ "p2p_total": 21
34
+ },
35
+ {
36
+ "instance_id": "swedl__semverlite-1",
37
+ "resolved": false,
38
+ "reason": "model patch failed to apply: empty patch",
39
+ "f2p_passed": 0,
40
+ "f2p_total": 7,
41
+ "p2p_passed": 0,
42
+ "p2p_total": 19
43
+ }
44
+ ]
45
+ }
reports/gold.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "SWE-DockerLess.jsonl",
3
+ "instances": 4,
4
+ "resolved": 4,
5
+ "resolve_rate": 1.0,
6
+ "seconds": 6.71,
7
+ "results": [
8
+ {
9
+ "instance_id": "swedl__miniconf-1",
10
+ "resolved": true,
11
+ "reason": "ok",
12
+ "f2p_passed": 9,
13
+ "f2p_total": 9,
14
+ "p2p_passed": 15,
15
+ "p2p_total": 15,
16
+ "failing": []
17
+ },
18
+ {
19
+ "instance_id": "swedl__ttlcache-1",
20
+ "resolved": true,
21
+ "reason": "ok",
22
+ "f2p_passed": 5,
23
+ "f2p_total": 5,
24
+ "p2p_passed": 12,
25
+ "p2p_total": 12,
26
+ "failing": []
27
+ },
28
+ {
29
+ "instance_id": "swedl__cronlite-1",
30
+ "resolved": true,
31
+ "reason": "ok",
32
+ "f2p_passed": 8,
33
+ "f2p_total": 8,
34
+ "p2p_passed": 21,
35
+ "p2p_total": 21,
36
+ "failing": []
37
+ },
38
+ {
39
+ "instance_id": "swedl__semverlite-1",
40
+ "resolved": true,
41
+ "reason": "ok",
42
+ "f2p_passed": 7,
43
+ "f2p_total": 7,
44
+ "p2p_passed": 19,
45
+ "p2p_total": 19,
46
+ "failing": []
47
+ }
48
+ ]
49
+ }
reports/partial.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "SWE-DockerLess.jsonl",
3
+ "instances": 4,
4
+ "resolved": 0,
5
+ "resolve_rate": 0.0,
6
+ "seconds": 11.23,
7
+ "results": [
8
+ {
9
+ "instance_id": "swedl__miniconf-1",
10
+ "resolved": false,
11
+ "reason": "unmet tests: 4",
12
+ "f2p_passed": 5,
13
+ "f2p_total": 9,
14
+ "p2p_passed": 15,
15
+ "p2p_total": 15,
16
+ "failing": [
17
+ "tests/test_interpolation_edge_cases.py::test_dollar_escape",
18
+ "tests/test_interpolation_edge_cases.py::test_escape_does_not_hide_a_real_cycle",
19
+ "tests/test_interpolation_edge_cases.py::test_escape_next_to_reference",
20
+ "tests/test_interpolation_edge_cases.py::test_escaped_text_is_not_reinterpolated_through_a_reference"
21
+ ]
22
+ },
23
+ {
24
+ "instance_id": "swedl__ttlcache-1",
25
+ "resolved": false,
26
+ "reason": "unmet tests: 3",
27
+ "f2p_passed": 2,
28
+ "f2p_total": 5,
29
+ "p2p_passed": 12,
30
+ "p2p_total": 12,
31
+ "failing": [
32
+ "tests/test_lru_semantics.py::test_get_refreshes_recency",
33
+ "tests/test_lru_semantics.py::test_items_reports_least_recently_used_first",
34
+ "tests/test_lru_semantics.py::test_setdefault_refreshes_recency"
35
+ ]
36
+ },
37
+ {
38
+ "instance_id": "swedl__cronlite-1",
39
+ "resolved": false,
40
+ "reason": "unmet tests: 2",
41
+ "f2p_passed": 6,
42
+ "f2p_total": 8,
43
+ "p2p_passed": 21,
44
+ "p2p_total": 21,
45
+ "failing": [
46
+ "tests/test_step_and_sunday.py::test_next_after_with_stepped_start",
47
+ "tests/test_step_and_sunday.py::test_single_value_with_step_runs_to_end_of_range"
48
+ ]
49
+ },
50
+ {
51
+ "instance_id": "swedl__semverlite-1",
52
+ "resolved": false,
53
+ "reason": "unmet tests: 4",
54
+ "f2p_passed": 3,
55
+ "f2p_total": 7,
56
+ "p2p_passed": 19,
57
+ "p2p_total": 19,
58
+ "failing": [
59
+ "tests/test_prerelease_precedence.py::test_prerelease_does_not_satisfy_caret_range",
60
+ "tests/test_prerelease_precedence.py::test_prerelease_does_not_satisfy_release_lower_bound",
61
+ "tests/test_prerelease_precedence.py::test_range_allows_prerelease_when_same_triple_is_named",
62
+ "tests/test_prerelease_precedence.py::test_tilde_range_excludes_prerelease"
63
+ ]
64
+ }
65
+ ]
66
+ }
repos/cronlite/README.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cronlite
2
+
3
+ A dependency-free evaluator for standard five-field cron expressions:
4
+
5
+ ```
6
+ minute hour day-of-month month day-of-week
7
+ ```
8
+
9
+ ## Field syntax
10
+
11
+ | Form | Meaning |
12
+ | --- | --- |
13
+ | `*` | every value in the field range |
14
+ | `7` | a single value |
15
+ | `1-5` | an inclusive range |
16
+ | `*/15` | every 15th value across the whole range |
17
+ | `1-10/3` | every 3rd value inside the range (`1, 4, 7, 10`) |
18
+ | `5/15` | every 15th value starting at 5 and **running to the end of the range** (`5, 20, 35, 50`) |
19
+ | `0,15,30` | a list; any of the above forms may be combined in a list |
20
+
21
+ Field ranges: minute `0-59`, hour `0-23`, day-of-month `1-31`, month `1-12`.
22
+
23
+ ## Day of week
24
+
25
+ The day-of-week field is `0-7` where **both `0` and `7` mean Sunday** and
26
+ `1-6` mean Monday to Saturday. `7` must be accepted anywhere a value is
27
+ accepted, including inside ranges such as `6-7` (Saturday and Sunday), and it
28
+ must behave exactly like `0`. Internally a parsed day-of-week set is expressed
29
+ on the `0-6` scale, so `parse_field(DAY_OF_WEEK, "7") == {0}` and
30
+ `parse_field(DAY_OF_WEEK, "6-7") == {6, 0}`.
31
+
32
+ ## Matching
33
+
34
+ `CronExpression.matches(moment)` is true when all five fields match. The
35
+ day-of-month and day-of-week fields are combined with AND (not the traditional
36
+ OR). `next_after(moment)` returns the first matching minute strictly after
37
+ `moment`, scanning forward up to 366 days.
38
+
39
+ ## Tests
40
+
41
+ ```
42
+ python -m pytest -q
43
+ ```
repos/cronlite/cronlite/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """cronlite - a dependency-free five-field cron expression evaluator."""
2
+
3
+ from .expr import CronExpression, cron_weekday, next_after
4
+ from .fields import (
5
+ DAY_OF_MONTH,
6
+ DAY_OF_WEEK,
7
+ HOUR,
8
+ MINUTE,
9
+ MONTH,
10
+ FieldSpec,
11
+ parse_field,
12
+ )
13
+
14
+ __version__ = "0.2.3"
15
+
16
+ __all__ = [
17
+ "CronExpression",
18
+ "DAY_OF_MONTH",
19
+ "DAY_OF_WEEK",
20
+ "FieldSpec",
21
+ "HOUR",
22
+ "MINUTE",
23
+ "MONTH",
24
+ "cron_weekday",
25
+ "next_after",
26
+ "parse_field",
27
+ ]
repos/cronlite/cronlite/expr.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A five-field cron expression evaluator."""
2
+
3
+ from datetime import timedelta
4
+
5
+ from .fields import DAY_OF_MONTH, DAY_OF_WEEK, HOUR, MINUTE, MONTH, parse_field
6
+
7
+ SEARCH_LIMIT_DAYS = 366
8
+
9
+
10
+ def cron_weekday(moment):
11
+ """Return the cron weekday of ``moment``: 0 = Sunday, 6 = Saturday."""
12
+ return (moment.weekday() + 1) % 7
13
+
14
+
15
+ class CronExpression:
16
+ """A parsed ``minute hour day-of-month month day-of-week`` expression."""
17
+
18
+ def __init__(self, expression):
19
+ parts = expression.split()
20
+ if len(parts) != 5:
21
+ raise ValueError("expected 5 fields, got %d" % (len(parts),))
22
+ self.expression = " ".join(parts)
23
+ self.minutes = parse_field(MINUTE, parts[0])
24
+ self.hours = parse_field(HOUR, parts[1])
25
+ self.days = parse_field(DAY_OF_MONTH, parts[2])
26
+ self.months = parse_field(MONTH, parts[3])
27
+ self.weekdays = parse_field(DAY_OF_WEEK, parts[4])
28
+
29
+ def matches(self, moment):
30
+ return (
31
+ moment.minute in self.minutes
32
+ and moment.hour in self.hours
33
+ and moment.day in self.days
34
+ and moment.month in self.months
35
+ and cron_weekday(moment) in self.weekdays
36
+ )
37
+
38
+ def next_after(self, moment):
39
+ """Return the first matching minute strictly after ``moment``."""
40
+ current = moment.replace(second=0, microsecond=0) + timedelta(minutes=1)
41
+ limit = current + timedelta(days=SEARCH_LIMIT_DAYS)
42
+ while current <= limit:
43
+ if self.matches(current):
44
+ return current
45
+ current += timedelta(minutes=1)
46
+ raise ValueError("no matching time within %d days" % SEARCH_LIMIT_DAYS)
47
+
48
+ def __str__(self):
49
+ return self.expression
50
+
51
+ def __repr__(self):
52
+ return "CronExpression(%r)" % (self.expression,)
53
+
54
+
55
+ def next_after(expression, moment):
56
+ """Convenience wrapper: ``next_after("*/5 * * * *", moment)``."""
57
+ if not isinstance(expression, CronExpression):
58
+ expression = CronExpression(expression)
59
+ return expression.next_after(moment)
repos/cronlite/cronlite/fields.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parsing of individual cron fields into sets of integers."""
2
+
3
+
4
+ class FieldSpec:
5
+ """Describes one of the five cron fields."""
6
+
7
+ def __init__(self, name, minimum, maximum):
8
+ self.name = name
9
+ self.minimum = minimum
10
+ self.maximum = maximum
11
+
12
+ def _check(self, value):
13
+ if value < self.minimum or value > self.maximum:
14
+ raise ValueError("%s value out of range: %d" % (self.name, value))
15
+ return value
16
+
17
+ def parse(self, text):
18
+ values = set()
19
+ for part in text.split(","):
20
+ part = part.strip()
21
+ if not part:
22
+ raise ValueError("empty %s component" % self.name)
23
+ values |= self._parse_part(part)
24
+ if not values:
25
+ raise ValueError("empty %s field" % self.name)
26
+ return values
27
+
28
+ def _parse_part(self, part):
29
+ if part == "*":
30
+ return set(range(self.minimum, self.maximum + 1))
31
+ if "/" in part:
32
+ base, _, step_text = part.partition("/")
33
+ try:
34
+ step = int(step_text)
35
+ except ValueError:
36
+ raise ValueError("invalid step in %s field: %r" % (self.name, part))
37
+ if step <= 0:
38
+ raise ValueError("step must be positive in %s field" % self.name)
39
+ if base == "*":
40
+ start, stop = self.minimum, self.maximum
41
+ elif "-" in base:
42
+ start, stop = self._parse_bounds(base)
43
+ else:
44
+ start = self._check(int(base))
45
+ stop = start
46
+ return set(range(start, stop + 1, step))
47
+ if "-" in part:
48
+ start, stop = self._parse_bounds(part)
49
+ return set(range(start, stop + 1))
50
+ return {self._check(int(part))}
51
+
52
+ def _parse_bounds(self, text):
53
+ low, _, high = text.partition("-")
54
+ try:
55
+ start, stop = int(low), int(high)
56
+ except ValueError:
57
+ raise ValueError("invalid range in %s field: %r" % (self.name, text))
58
+ self._check(start)
59
+ self._check(stop)
60
+ if stop < start:
61
+ raise ValueError("descending range in %s field: %r" % (self.name, text))
62
+ return start, stop
63
+
64
+
65
+ MINUTE = FieldSpec("minute", 0, 59)
66
+ HOUR = FieldSpec("hour", 0, 23)
67
+ DAY_OF_MONTH = FieldSpec("day_of_month", 1, 31)
68
+ MONTH = FieldSpec("month", 1, 12)
69
+ DAY_OF_WEEK = FieldSpec("day_of_week", 0, 6)
70
+
71
+
72
+ def parse_field(spec, text):
73
+ """Parse ``text`` against ``spec`` and return the matching values."""
74
+ return spec.parse(text)
repos/cronlite/tests/test_basic.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import pytest
4
+
5
+ from cronlite import CronExpression, cron_weekday, next_after
6
+ from cronlite.fields import DAY_OF_WEEK, HOUR, MINUTE, parse_field
7
+
8
+
9
+ def test_star_field():
10
+ assert parse_field(MINUTE, "*") == set(range(60))
11
+
12
+
13
+ def test_single_value_field():
14
+ assert parse_field(MINUTE, "17") == {17}
15
+
16
+
17
+ def test_list_field():
18
+ assert parse_field(MINUTE, "0,15,30,45") == {0, 15, 30, 45}
19
+
20
+
21
+ def test_list_with_range():
22
+ assert parse_field(MINUTE, "0,10-12") == {0, 10, 11, 12}
23
+
24
+
25
+ def test_range_field():
26
+ assert parse_field(HOUR, "9-11") == {9, 10, 11}
27
+
28
+
29
+ def test_star_step_field():
30
+ assert parse_field(MINUTE, "*/15") == {0, 15, 30, 45}
31
+
32
+
33
+ def test_range_step_field():
34
+ assert parse_field(MINUTE, "1-10/3") == {1, 4, 7, 10}
35
+
36
+
37
+ def test_out_of_range_rejected():
38
+ with pytest.raises(ValueError):
39
+ parse_field(MINUTE, "60")
40
+ with pytest.raises(ValueError):
41
+ parse_field(HOUR, "24")
42
+
43
+
44
+ def test_bad_step_rejected():
45
+ with pytest.raises(ValueError):
46
+ parse_field(MINUTE, "*/0")
47
+
48
+
49
+ def test_descending_range_rejected():
50
+ with pytest.raises(ValueError):
51
+ parse_field(MINUTE, "10-1")
52
+
53
+
54
+ def test_weekday_field_within_zero_to_six():
55
+ assert parse_field(DAY_OF_WEEK, "1-5") == {1, 2, 3, 4, 5}
56
+
57
+
58
+ def test_cron_weekday_mapping():
59
+ assert cron_weekday(datetime(2026, 3, 4)) == 3
60
+ assert cron_weekday(datetime(2026, 3, 8)) == 0
61
+
62
+
63
+ def test_matches_every_minute():
64
+ expr = CronExpression("* * * * *")
65
+ assert expr.matches(datetime(2026, 3, 4, 5, 6))
66
+
67
+
68
+ def test_matches_rejects_wrong_minute():
69
+ expr = CronExpression("30 9 * * *")
70
+ assert not expr.matches(datetime(2026, 3, 4, 9, 31))
71
+
72
+
73
+ def test_next_after_basic():
74
+ expr = CronExpression("30 9 * * *")
75
+ assert next_after(expr, datetime(2026, 3, 4, 5, 6)) == datetime(2026, 3, 4, 9, 30)
76
+
77
+
78
+ def test_next_after_is_strict():
79
+ expr = CronExpression("30 9 * * *")
80
+ assert next_after(expr, datetime(2026, 3, 4, 9, 30)) == datetime(2026, 3, 5, 9, 30)
81
+
82
+
83
+ def test_next_after_rolls_to_next_day():
84
+ expr = CronExpression("0 0 * * *")
85
+ assert next_after(expr, datetime(2026, 3, 4, 0, 0)) == datetime(2026, 3, 5, 0, 0)
86
+
87
+
88
+ def test_next_after_accepts_string():
89
+ assert next_after("*/30 * * * *", datetime(2026, 3, 4, 5, 6)) == datetime(2026, 3, 4, 5, 30)
90
+
91
+
92
+ def test_invalid_field_count():
93
+ with pytest.raises(ValueError):
94
+ CronExpression("* * * *")
95
+
96
+
97
+ def test_str_roundtrip():
98
+ assert str(CronExpression(" 0 12 * * * ")) == "0 12 * * *"
repos/miniconf/README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # miniconf
2
+
3
+ A tiny layered configuration library. Values may reference other keys with
4
+ `${key}` and are resolved lazily on access.
5
+
6
+ ## Interpolation contract
7
+
8
+ This is the documented behaviour of `Config`; `tests/` covers the common cases.
9
+
10
+ 1. **References.** A string value may contain any number of `${key}` references.
11
+ The reference is replaced by the *fully resolved* value of `key`, stringified
12
+ with `str()`. References may chain: `a` -> `b` -> `c`.
13
+ 2. **Single pass.** Substituted text is never scanned again for references. If
14
+ `inner` resolves to the literal text `${leak}`, then `"${inner}"` resolves to
15
+ `${leak}` and not to the value of `leak`.
16
+ 3. **Escaping.** `$$` is an escape that produces a single literal `$`. It never
17
+ starts a reference, so `"$${amount}"` resolves to the five characters
18
+ `${amount}` — the reference is *not* expanded. `"$${name} is ${name}"` with
19
+ `name=wren` resolves to `"${name} is wren"`.
20
+ 4. **Cycles.** A reference cycle, including a self reference such as
21
+ `a = "x${a}"`, must raise `CircularReferenceError` instead of recursing. The
22
+ message is `"circular reference: "` followed by the key chain joined with
23
+ `" -> "`, starting at the key the caller asked for and ending with that same
24
+ key repeated. Asking for `a` where `a -> b -> a` raises
25
+ `"circular reference: a -> b -> a"`; asking for `a` where `a -> a` raises
26
+ `"circular reference: a -> a"`.
27
+ 5. **Missing keys.** A reference to an unknown key raises `MissingKeyError`.
28
+ 6. **Non-string values** are returned as-is and are never scanned.
29
+
30
+ `Config.as_dict()` resolves every key, so any cycle or missing reference in the
31
+ mapping surfaces there too. A cycle that is unrelated to the key being read must
32
+ not affect that read: with `a="fine"`, `b="${c}"`, `c="${b}"`, reading `a` still
33
+ returns `"fine"` while reading `b` raises.
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ from miniconf import Config
39
+
40
+ cfg = Config.from_layers(
41
+ {"host": "localhost", "port": 8080},
42
+ {"url": "http://${host}:${port}/"},
43
+ )
44
+ cfg["url"] # 'http://localhost:8080/'
45
+ cfg.as_dict() # {'host': 'localhost', 'port': 8080, 'url': 'http://localhost:8080/'}
46
+ ```
47
+
48
+ ## Tests
49
+
50
+ ```
51
+ python -m pytest -q
52
+ ```
repos/miniconf/miniconf/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """miniconf - a tiny layered configuration library with string interpolation."""
2
+
3
+ from .config import Config
4
+ from .errors import (
5
+ CircularReferenceError,
6
+ ConfigError,
7
+ InterpolationError,
8
+ MissingKeyError,
9
+ )
10
+ from .loader import load_layers
11
+
12
+ __version__ = "0.4.1"
13
+
14
+ __all__ = [
15
+ "CircularReferenceError",
16
+ "Config",
17
+ "ConfigError",
18
+ "InterpolationError",
19
+ "MissingKeyError",
20
+ "load_layers",
21
+ ]
repos/miniconf/miniconf/config.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Config object: layered key/value storage with ${...} interpolation."""
2
+
3
+ import re
4
+
5
+ from .errors import MissingKeyError
6
+ from .loader import load_layers
7
+
8
+ REFERENCE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_.-]*)\}")
9
+
10
+
11
+ class Config:
12
+ """A small configuration mapping whose string values may reference keys.
13
+
14
+ See README.md for the interpolation contract.
15
+ """
16
+
17
+ def __init__(self, data):
18
+ if not isinstance(data, dict):
19
+ raise TypeError("Config data must be a dict")
20
+ self._raw = dict(data)
21
+
22
+ @classmethod
23
+ def from_layers(cls, *layers):
24
+ """Build a Config from one or more dict layers, later layers winning."""
25
+ return cls(load_layers(*layers))
26
+
27
+ def raw(self, key, default=None):
28
+ """Return the unresolved value stored under ``key``."""
29
+ return self._raw.get(key, default)
30
+
31
+ def keys(self):
32
+ return list(self._raw)
33
+
34
+ def get(self, key, default=None):
35
+ if key not in self._raw:
36
+ return default
37
+ return self._resolve(key)
38
+
39
+ def __getitem__(self, key):
40
+ if key not in self._raw:
41
+ raise KeyError(key)
42
+ return self._resolve(key)
43
+
44
+ def __contains__(self, key):
45
+ return key in self._raw
46
+
47
+ def __len__(self):
48
+ return len(self._raw)
49
+
50
+ def as_dict(self):
51
+ """Return every key resolved to a plain value."""
52
+ return {key: self._resolve(key) for key in self._raw}
53
+
54
+ def _resolve(self, key):
55
+ value = self._raw[key]
56
+ if not isinstance(value, str):
57
+ return value
58
+ return self._interpolate(value, key)
59
+
60
+ def _interpolate(self, text, origin):
61
+ def replace(match):
62
+ name = match.group(1)
63
+ if name not in self._raw:
64
+ raise MissingKeyError(name, origin)
65
+ return str(self._resolve(name))
66
+
67
+ return REFERENCE.sub(replace, text)
repos/miniconf/miniconf/errors.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exception hierarchy for miniconf."""
2
+
3
+
4
+ class ConfigError(Exception):
5
+ """Base class for every error raised by miniconf."""
6
+
7
+
8
+ class InterpolationError(ConfigError):
9
+ """Raised when a ``${...}`` reference cannot be resolved."""
10
+
11
+
12
+ class MissingKeyError(InterpolationError):
13
+ """Raised when a reference points at a key that does not exist."""
14
+
15
+ def __init__(self, key, referenced_from=None):
16
+ self.key = key
17
+ self.referenced_from = referenced_from
18
+ if referenced_from is None:
19
+ message = "missing key: %r" % (key,)
20
+ else:
21
+ message = "missing key %r referenced from %r" % (key, referenced_from)
22
+ super().__init__(message)
23
+
24
+
25
+ class CircularReferenceError(InterpolationError):
26
+ """Raised when interpolation would loop forever."""
27
+
28
+ def __init__(self, cycle):
29
+ self.cycle = list(cycle)
30
+ super().__init__("circular reference: " + " -> ".join(self.cycle))
repos/miniconf/miniconf/loader.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer merging for miniconf configuration dicts."""
2
+
3
+ from .errors import ConfigError
4
+
5
+
6
+ def load_layers(*layers):
7
+ """Merge configuration layers left to right; later layers win."""
8
+ merged = {}
9
+ for layer in layers:
10
+ if not isinstance(layer, dict):
11
+ raise ConfigError("layer must be a dict, got %r" % (type(layer).__name__,))
12
+ for key, value in layer.items():
13
+ merged[key] = value
14
+ return merged
repos/miniconf/tests/test_basic.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from miniconf import Config, ConfigError, MissingKeyError, load_layers
4
+
5
+
6
+ def test_plain_values():
7
+ cfg = Config({"name": "app", "port": 8080})
8
+ assert cfg["name"] == "app"
9
+ assert cfg["port"] == 8080
10
+ assert len(cfg) == 2
11
+
12
+
13
+ def test_simple_reference():
14
+ cfg = Config({"host": "localhost", "url": "http://${host}/"})
15
+ assert cfg["url"] == "http://localhost/"
16
+
17
+
18
+ def test_two_references_in_one_value():
19
+ cfg = Config({"host": "db", "port": 5432, "dsn": "${host}:${port}"})
20
+ assert cfg["dsn"] == "db:5432"
21
+
22
+
23
+ def test_chained_reference():
24
+ cfg = Config({"a": "x", "b": "${a}-y", "c": "${b}-z"})
25
+ assert cfg["c"] == "x-y-z"
26
+
27
+
28
+ def test_missing_key_raises():
29
+ cfg = Config({"a": "${nope}"})
30
+ with pytest.raises(MissingKeyError):
31
+ cfg["a"]
32
+
33
+
34
+ def test_missing_key_message():
35
+ cfg = Config({"a": "${nope}"})
36
+ with pytest.raises(MissingKeyError) as excinfo:
37
+ cfg["a"]
38
+ assert str(excinfo.value) == "missing key 'nope' referenced from 'a'"
39
+
40
+
41
+ def test_non_string_passthrough():
42
+ cfg = Config({"n": 3, "flag": True, "nested": {"x": 1}})
43
+ assert cfg["n"] == 3
44
+ assert cfg["flag"] is True
45
+ assert cfg["nested"] == {"x": 1}
46
+
47
+
48
+ def test_get_returns_default_for_unknown_key():
49
+ cfg = Config({"a": "1"})
50
+ assert cfg.get("zzz") is None
51
+ assert cfg.get("zzz", "dflt") == "dflt"
52
+
53
+
54
+ def test_getitem_raises_keyerror_for_unknown_key():
55
+ cfg = Config({"a": "1"})
56
+ with pytest.raises(KeyError):
57
+ cfg["zzz"]
58
+
59
+
60
+ def test_raw_does_not_resolve():
61
+ cfg = Config({"a": "1", "b": "${a}"})
62
+ assert cfg.raw("b") == "${a}"
63
+
64
+
65
+ def test_from_layers_override():
66
+ cfg = Config.from_layers({"a": "1", "b": "2"}, {"b": "3"})
67
+ assert cfg.as_dict() == {"a": "1", "b": "3"}
68
+
69
+
70
+ def test_load_layers_rejects_non_dict():
71
+ with pytest.raises(ConfigError):
72
+ load_layers({"a": 1}, ["not", "a", "dict"])
73
+
74
+
75
+ def test_as_dict_resolves_all():
76
+ cfg = Config({"a": "1", "b": "${a}2"})
77
+ assert cfg.as_dict() == {"a": "1", "b": "12"}
78
+
79
+
80
+ def test_config_rejects_non_dict():
81
+ with pytest.raises(TypeError):
82
+ Config([("a", 1)])
repos/semverlite/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # semverlite
2
+
3
+ Semantic version parsing, precedence and range matching, following
4
+ [semver 2.0.0](https://semver.org/).
5
+
6
+ ## Precedence
7
+
8
+ `Version` objects sort by semver precedence:
9
+
10
+ 1. Compare `major`, then `minor`, then `patch` numerically.
11
+ 2. A version **with** a prerelease is lower than the same version without one
12
+ (`1.0.0-alpha < 1.0.0`).
13
+ 3. Prerelease identifiers are compared left to right. A **numeric** identifier
14
+ always compares numerically, so `1.0.0-alpha.2 < 1.0.0-alpha.10`. An
15
+ alphanumeric identifier compares by ASCII order and is always **greater**
16
+ than a numeric identifier of the same position (`1.0.0-1 < 1.0.0-alpha`).
17
+ A longer prerelease wins when all shared identifiers are equal
18
+ (`1.0.0-alpha < 1.0.0-alpha.1`).
19
+ 4. Build metadata is ignored for precedence, so `1.0.0+a == 1.0.0+b`.
20
+
21
+ ## Ranges
22
+
23
+ `VersionRange(text)` accepts a comma-separated conjunction of clauses using
24
+ `=`, `==`, `>`, `>=`, `<`, `<=`, `^` and `~`. `^1.2.3` means
25
+ `>=1.2.3, <2.0.0`; `~1.2.3` means `>=1.2.3, <1.3.0`.
26
+
27
+ **Prereleases are excluded from a range unless the range itself opts in.** A
28
+ version carrying a prerelease satisfies the range only when some clause names a
29
+ prerelease with the *same* `major.minor.patch` triple. So `>=1.0.0` does not
30
+ allow `1.0.1-alpha`, while `>=1.0.0-alpha` does allow `1.0.0-beta`.
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from semverlite import Version, VersionRange
36
+
37
+ Version.parse("1.2.3-alpha.1") < Version.parse("1.2.3")
38
+ Version.parse("1.2.3") in VersionRange(">=1.0.0, <2.0.0")
39
+ ```
40
+
41
+ ## Tests
42
+
43
+ ```
44
+ python -m pytest -q
45
+ ```
repos/semverlite/semverlite/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """semverlite - semantic version parsing, precedence and ranges."""
2
+
3
+ from .range import VersionRange
4
+ from .version import Version
5
+
6
+ __version__ = "0.5.2"
7
+
8
+ __all__ = ["Version", "VersionRange"]
repos/semverlite/semverlite/range.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Version range expressions such as ``">=1.2.3, <2.0.0"``."""
2
+
3
+ import re
4
+
5
+ from .version import Version
6
+
7
+ _CLAUSE_RE = re.compile(r"^(>=|<=|==|=|>|<|\^|~)?\s*(\S+)$")
8
+
9
+
10
+ def _parse_clause(text):
11
+ match = _CLAUSE_RE.match(text)
12
+ if match is None:
13
+ raise ValueError("invalid range clause: %r" % (text,))
14
+ operator = match.group(1) or "=="
15
+ return operator, Version.parse(match.group(2))
16
+
17
+
18
+ def _caret_upper(target):
19
+ """Upper bound of ``^target``: the next release that breaks the left-most
20
+ non-zero component."""
21
+ if target.major > 0:
22
+ return Version(target.major + 1, 0, 0)
23
+ if target.minor > 0:
24
+ return Version(0, target.minor + 1, 0)
25
+ return Version(0, 0, target.patch + 1)
26
+
27
+
28
+ def _tilde_upper(target):
29
+ """Upper bound of ``~target``: the next minor release."""
30
+ return Version(target.major, target.minor + 1, 0)
31
+
32
+
33
+ class VersionRange:
34
+ """A comma-separated list of clauses that must all hold."""
35
+
36
+ def __init__(self, text):
37
+ self.text = text.strip()
38
+ parts = [part.strip() for part in self.text.split(",") if part.strip()]
39
+ if not parts:
40
+ raise ValueError("empty range")
41
+ self.clauses = [_parse_clause(part) for part in parts]
42
+
43
+ def allows(self, version):
44
+ return all(self._allows_clause(op, target, version) for op, target in self.clauses)
45
+
46
+ @staticmethod
47
+ def _allows_clause(operator, target, version):
48
+ if operator in ("=", "=="):
49
+ return version == target
50
+ if operator == ">":
51
+ return version > target
52
+ if operator == ">=":
53
+ return version >= target
54
+ if operator == "<":
55
+ return version < target
56
+ if operator == "<=":
57
+ return version <= target
58
+ if operator == "^":
59
+ return target <= version < _caret_upper(target)
60
+ if operator == "~":
61
+ return target <= version < _tilde_upper(target)
62
+ raise ValueError("unknown operator: %r" % (operator,))
63
+
64
+ def __contains__(self, version):
65
+ return self.allows(version)
66
+
67
+ def __str__(self):
68
+ return self.text
69
+
70
+ def __repr__(self):
71
+ return "VersionRange(%r)" % (self.text,)
repos/semverlite/semverlite/version.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Semantic version parsing and precedence."""
2
+
3
+ import re
4
+
5
+ _VERSION_RE = re.compile(
6
+ r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
7
+ r"(?:-(?P<pre>[0-9A-Za-z.-]+))?"
8
+ r"(?:\+(?P<build>[0-9A-Za-z.-]+))?$"
9
+ )
10
+
11
+
12
+ class Version:
13
+ """A semantic version: major.minor.patch[-prerelease][+build]."""
14
+
15
+ def __init__(self, major, minor, patch, prerelease=(), build=()):
16
+ self.major = int(major)
17
+ self.minor = int(minor)
18
+ self.patch = int(patch)
19
+ self.prerelease = tuple(prerelease)
20
+ self.build = tuple(build)
21
+
22
+ @classmethod
23
+ def parse(cls, text):
24
+ match = _VERSION_RE.match(text.strip())
25
+ if match is None:
26
+ raise ValueError("invalid version: %r" % (text,))
27
+ prerelease = tuple(match.group("pre").split(".")) if match.group("pre") else ()
28
+ build = tuple(match.group("build").split(".")) if match.group("build") else ()
29
+ return cls(
30
+ match.group("major"),
31
+ match.group("minor"),
32
+ match.group("patch"),
33
+ prerelease,
34
+ build,
35
+ )
36
+
37
+ @property
38
+ def core(self):
39
+ """The (major, minor, patch) triple."""
40
+ return (self.major, self.minor, self.patch)
41
+
42
+ def precedence_key(self):
43
+ """Sort key implementing semver precedence (build metadata ignored)."""
44
+ core = self.core
45
+ if not self.prerelease:
46
+ return core + (1, ())
47
+ return core + (0, tuple(str(part) for part in self.prerelease))
48
+
49
+ def __str__(self):
50
+ text = "%d.%d.%d" % self.core
51
+ if self.prerelease:
52
+ text += "-" + ".".join(str(part) for part in self.prerelease)
53
+ if self.build:
54
+ text += "+" + ".".join(str(part) for part in self.build)
55
+ return text
56
+
57
+ def __repr__(self):
58
+ return "Version(%r)" % (str(self),)
59
+
60
+ def __eq__(self, other):
61
+ if not isinstance(other, Version):
62
+ return NotImplemented
63
+ return self.precedence_key() == other.precedence_key()
64
+
65
+ def __ne__(self, other):
66
+ result = self.__eq__(other)
67
+ if result is NotImplemented:
68
+ return result
69
+ return not result
70
+
71
+ def __lt__(self, other):
72
+ return self.precedence_key() < other.precedence_key()
73
+
74
+ def __le__(self, other):
75
+ return self.precedence_key() <= other.precedence_key()
76
+
77
+ def __gt__(self, other):
78
+ return self.precedence_key() > other.precedence_key()
79
+
80
+ def __ge__(self, other):
81
+ return self.precedence_key() >= other.precedence_key()
82
+
83
+ def __hash__(self):
84
+ return hash(self.precedence_key())
repos/semverlite/tests/test_version.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from semverlite import Version, VersionRange
4
+
5
+
6
+ def v(text):
7
+ return Version.parse(text)
8
+
9
+
10
+ def test_parse_basic():
11
+ version = v("1.2.3")
12
+ assert version.major == 1
13
+ assert version.minor == 2
14
+ assert version.patch == 3
15
+ assert version.prerelease == ()
16
+ assert version.build == ()
17
+
18
+
19
+ def test_parse_prerelease_and_build():
20
+ version = v("1.2.3-rc.1+build.5")
21
+ assert version.prerelease == ("rc", "1")
22
+ assert version.build == ("build", "5")
23
+ assert version.core == (1, 2, 3)
24
+
25
+
26
+ def test_str_roundtrip():
27
+ for text in ("0.0.1", "1.2.3-alpha", "1.2.3-alpha.1+build.5"):
28
+ assert str(v(text)) == text
29
+
30
+
31
+ def test_invalid_versions_rejected():
32
+ for text in ("1.2", "1.2.3.4", "v1.2.3", "1.2.x"):
33
+ with pytest.raises(ValueError):
34
+ Version.parse(text)
35
+
36
+
37
+ def test_ordering_by_patch():
38
+ assert v("1.2.3") < v("1.2.4")
39
+
40
+
41
+ def test_ordering_by_minor():
42
+ assert v("1.2.9") < v("1.3.0")
43
+
44
+
45
+ def test_ordering_by_major():
46
+ assert v("1.9.9") < v("2.0.0")
47
+
48
+
49
+ def test_release_beats_prerelease():
50
+ assert v("1.0.0-alpha") < v("1.0.0")
51
+ assert v("1.0.0") > v("1.0.0-rc.9")
52
+
53
+
54
+ def test_shorter_prerelease_is_lower():
55
+ assert v("1.0.0-alpha") < v("1.0.0-alpha.1")
56
+
57
+
58
+ def test_equality_ignores_build_metadata():
59
+ assert v("1.0.0+a") == v("1.0.0+b")
60
+ assert v("1.0.0-alpha+x") == v("1.0.0-alpha+y")
61
+
62
+
63
+ def test_equality_and_hash():
64
+ assert v("1.2.3") == v("1.2.3")
65
+ assert len({v("1.2.3"), v("1.2.3")}) == 1
66
+
67
+
68
+ def test_inequality():
69
+ assert v("1.2.3") != v("1.2.4")
70
+
71
+
72
+ def test_range_lower_and_upper_bound():
73
+ version_range = VersionRange(">=1.0.0, <2.0.0")
74
+ assert version_range.allows(v("1.0.0"))
75
+ assert version_range.allows(v("1.5.0"))
76
+ assert not version_range.allows(v("2.0.0"))
77
+ assert not version_range.allows(v("0.9.9"))
78
+
79
+
80
+ def test_range_membership_operator():
81
+ assert v("1.5.0") in VersionRange(">=1.0.0, <2.0.0")
82
+ assert v("2.5.0") not in VersionRange(">=1.0.0, <2.0.0")
83
+
84
+
85
+ def test_caret_range():
86
+ version_range = VersionRange("^1.2.3")
87
+ assert version_range.allows(v("1.2.3"))
88
+ assert version_range.allows(v("1.9.9"))
89
+ assert not version_range.allows(v("2.0.0"))
90
+ assert not version_range.allows(v("1.2.2"))
91
+
92
+
93
+ def test_tilde_range():
94
+ version_range = VersionRange("~1.2.3")
95
+ assert version_range.allows(v("1.2.9"))
96
+ assert not version_range.allows(v("1.3.0"))
97
+
98
+
99
+ def test_exact_clause():
100
+ assert VersionRange("==1.2.3").allows(v("1.2.3"))
101
+ assert not VersionRange("==1.2.3").allows(v("1.2.4"))
102
+
103
+
104
+ def test_invalid_clause_rejected():
105
+ with pytest.raises(ValueError):
106
+ VersionRange(">=nope")
repos/ttlcache/README.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ttlcache
2
+
3
+ A bounded cache with per-entry time-to-live and LRU eviction. The cache never
4
+ reads the system clock directly; pass a `clock` object exposing `now()` (see
5
+ `ttlcache.clock.FakeClock`) so expiry is deterministic under test.
6
+
7
+ ## Contract
8
+
9
+ 1. **Expiry.** An entry written at time `t` is live while `now < t + ttl` and
10
+ expired once `now >= t + ttl`. Reading an expired key deletes it and raises
11
+ `KeyError` (`get` returns its default instead). `key in cache` is `False` for
12
+ expired entries.
13
+ 2. **Recency.** `__getitem__`, `get` and `setdefault` mark the entry as most
14
+ recently used. Writing an existing key also moves it to the most-recently-used
15
+ end *and* restarts its TTL.
16
+ 3. **Eviction.** When a write would exceed `maxsize`, expired entries are dropped
17
+ first; if the cache is still full, the least recently used live entry is
18
+ dropped.
19
+ 4. **`len(cache)`** counts live entries only. Expired-but-not-yet-collected
20
+ entries must not inflate the count.
21
+ 5. **`items()`** yields live pairs in LRU order (least recently used first).
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+ from ttlcache import FakeClock, TTLCache
27
+
28
+ clock = FakeClock()
29
+ cache = TTLCache(maxsize=2, ttl=10.0, clock=clock)
30
+ cache["a"] = 1
31
+ cache["b"] = 2
32
+ cache["a"] # 'a' is now most recently used
33
+ cache["c"] = 3 # evicts 'b', not 'a'
34
+ ```
35
+
36
+ ## Tests
37
+
38
+ ```
39
+ python -m pytest -q
40
+ ```
repos/ttlcache/tests/test_cache.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from ttlcache import FakeClock, TTLCache
4
+
5
+
6
+ def make(clock, maxsize=3, ttl=10.0):
7
+ return TTLCache(maxsize=maxsize, ttl=ttl, clock=clock)
8
+
9
+
10
+ def test_set_and_get():
11
+ clock = FakeClock()
12
+ cache = make(clock)
13
+ cache["a"] = 1
14
+ assert cache["a"] == 1
15
+ assert cache.get("a") == 1
16
+
17
+
18
+ def test_missing_key_returns_default():
19
+ cache = make(FakeClock())
20
+ assert cache.get("nope") is None
21
+ assert cache.get("nope", 7) == 7
22
+
23
+
24
+ def test_getitem_raises_for_missing_key():
25
+ cache = make(FakeClock())
26
+ with pytest.raises(KeyError):
27
+ cache["nope"]
28
+
29
+
30
+ def test_entry_expires():
31
+ clock = FakeClock()
32
+ cache = make(clock)
33
+ cache["a"] = 1
34
+ clock.advance(10)
35
+ assert "a" not in cache
36
+ assert cache.get("a") is None
37
+ with pytest.raises(KeyError):
38
+ cache["a"]
39
+
40
+
41
+ def test_entry_survives_before_deadline():
42
+ clock = FakeClock()
43
+ cache = make(clock)
44
+ cache["a"] = 1
45
+ clock.advance(9.5)
46
+ assert cache["a"] == 1
47
+
48
+
49
+ def test_eviction_order_on_insert():
50
+ clock = FakeClock()
51
+ cache = make(clock, maxsize=2)
52
+ cache["a"] = 1
53
+ cache["b"] = 2
54
+ cache["c"] = 3
55
+ assert "a" not in cache
56
+ assert "b" in cache and "c" in cache
57
+
58
+
59
+ def test_overwrite_updates_value():
60
+ clock = FakeClock()
61
+ cache = make(clock)
62
+ cache["a"] = 1
63
+ cache["a"] = 2
64
+ assert cache["a"] == 2
65
+ assert len(cache) == 1
66
+
67
+
68
+ def test_setdefault_uses_factory_once():
69
+ clock = FakeClock()
70
+ cache = make(clock)
71
+ calls = []
72
+
73
+ def factory():
74
+ calls.append(1)
75
+ return "v"
76
+
77
+ assert cache.setdefault("k", factory) == "v"
78
+ assert cache.setdefault("k", factory) == "v"
79
+ assert len(calls) == 1
80
+
81
+
82
+ def test_pop_removes_entry():
83
+ clock = FakeClock()
84
+ cache = make(clock)
85
+ cache["a"] = 1
86
+ assert cache.pop("a") == 1
87
+ assert cache.pop("a", "gone") == "gone"
88
+
89
+
90
+ def test_items_skips_expired():
91
+ clock = FakeClock()
92
+ cache = make(clock)
93
+ cache["a"] = 1
94
+ clock.advance(4)
95
+ cache["b"] = 2
96
+ clock.advance(7)
97
+ assert list(cache.items()) == [("b", 2)]
98
+
99
+
100
+ def test_invalid_arguments():
101
+ with pytest.raises(ValueError):
102
+ TTLCache(maxsize=0)
103
+ with pytest.raises(ValueError):
104
+ TTLCache(ttl=0)
105
+
106
+
107
+ def test_repr_reports_live_count():
108
+ clock = FakeClock()
109
+ cache = make(clock)
110
+ cache["a"] = 1
111
+ assert "live=1" in repr(cache)
repos/ttlcache/ttlcache/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """ttlcache - a bounded TTL + LRU cache."""
2
+
3
+ from .cache import TTLCache
4
+ from .clock import FakeClock, SystemClock
5
+
6
+ __version__ = "0.3.0"
7
+
8
+ __all__ = ["FakeClock", "SystemClock", "TTLCache"]
repos/ttlcache/ttlcache/cache.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A bounded cache with per-entry time-to-live and LRU eviction."""
2
+
3
+ from collections import OrderedDict
4
+
5
+
6
+ class TTLCache:
7
+ """Fixed-capacity cache where every entry expires ``ttl`` seconds after write.
8
+
9
+ Entries are kept in least-recently-used order. When the cache is full the
10
+ least recently used entry is dropped first. See README.md for the full
11
+ contract.
12
+ """
13
+
14
+ def __init__(self, maxsize=128, ttl=60.0, clock=None):
15
+ if maxsize <= 0:
16
+ raise ValueError("maxsize must be positive")
17
+ if ttl <= 0:
18
+ raise ValueError("ttl must be positive")
19
+ self.maxsize = maxsize
20
+ self.ttl = float(ttl)
21
+ self._clock = clock
22
+ self._data = OrderedDict()
23
+
24
+ def _now(self):
25
+ return self._clock.now() if self._clock is not None else 0.0
26
+
27
+ @staticmethod
28
+ def _expired(deadline, now):
29
+ return now >= deadline
30
+
31
+ def __len__(self):
32
+ return len(self._data)
33
+
34
+ def __contains__(self, key):
35
+ if key not in self._data:
36
+ return False
37
+ _, deadline = self._data[key]
38
+ return not self._expired(deadline, self._now())
39
+
40
+ def __setitem__(self, key, value):
41
+ now = self._now()
42
+ self._data[key] = (value, now + self.ttl)
43
+ while len(self._data) > self.maxsize:
44
+ self._data.popitem(last=False)
45
+
46
+ def __getitem__(self, key):
47
+ value, deadline = self._data[key]
48
+ if self._expired(deadline, self._now()):
49
+ del self._data[key]
50
+ raise KeyError(key)
51
+ return value
52
+
53
+ def get(self, key, default=None):
54
+ try:
55
+ return self[key]
56
+ except KeyError:
57
+ return default
58
+
59
+ def setdefault(self, key, factory):
60
+ """Return the live value for ``key``, computing and storing it if absent."""
61
+ if key in self:
62
+ return self[key]
63
+ value = factory()
64
+ self[key] = value
65
+ return value
66
+
67
+ def pop(self, key, default=None):
68
+ if key not in self._data:
69
+ return default
70
+ value, _ = self._data.pop(key)
71
+ return value
72
+
73
+ def items(self):
74
+ """Iterate over live ``(key, value)`` pairs in LRU order."""
75
+ now = self._now()
76
+ return [(k, v) for k, (v, d) in self._data.items() if not self._expired(d, now)]
77
+
78
+ def __repr__(self):
79
+ return "TTLCache(maxsize=%d, ttl=%r, live=%d)" % (
80
+ self.maxsize,
81
+ self.ttl,
82
+ len(self),
83
+ )
repos/ttlcache/ttlcache/clock.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clocks used by ttlcache.
2
+
3
+ The cache never calls ``time`` directly: it asks a clock object for the current
4
+ time, which makes expiry deterministic in tests.
5
+ """
6
+
7
+ import time
8
+
9
+
10
+ class SystemClock:
11
+ """Monotonic wall clock for production use."""
12
+
13
+ def now(self):
14
+ return time.monotonic()
15
+
16
+
17
+ class FakeClock:
18
+ """A clock that only moves when you tell it to."""
19
+
20
+ def __init__(self, start=0.0):
21
+ self._now = float(start)
22
+
23
+ def now(self):
24
+ return self._now
25
+
26
+ def advance(self, seconds):
27
+ self._now += float(seconds)
28
+ return self._now
run_harness.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SWE-DockerLess evaluation harness.
2
+
3
+ No Docker, no network, no prebuilt images: every instance carries its own repo
4
+ snapshot inside the JSONL row, so the harness only needs Python, git and pytest.
5
+
6
+ Usage
7
+ -----
8
+ # sanity check: score the gold patches (expect 4/4 resolved)
9
+ python run_harness.py --dataset SWE-DockerLess.jsonl --gold
10
+
11
+ # score a predictions file: one JSON object per line with
12
+ # {"instance_id": ..., "model_name_or_path": ..., "model_patch": ...}
13
+ python run_harness.py --dataset SWE-DockerLess.jsonl \
14
+ --predictions predictions.jsonl --out report.json
15
+
16
+ A prediction is "resolved" when every FAIL_TO_PASS test passes and every
17
+ PASS_TO_PASS test still passes, which is the SWE-bench rule.
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import re
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ import time
29
+ from pathlib import Path
30
+
31
+ GIT_FLAGS = [
32
+ "-c", "core.autocrlf=false",
33
+ "-c", "core.safecrlf=false",
34
+ "-c", "user.name=harness",
35
+ "-c", "user.email=harness@example.invalid",
36
+ "-c", "commit.gpgsign=false",
37
+ ]
38
+
39
+ RESULT_RE = re.compile(
40
+ r"^(tests/[^\s:]+::[^\s]+)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)"
41
+ )
42
+
43
+
44
+ def run(cmd, cwd, check=True):
45
+ env = os.environ.copy()
46
+ env.setdefault("GIT_AUTHOR_NAME", "harness")
47
+ env.setdefault("GIT_AUTHOR_EMAIL", "harness@example.invalid")
48
+ env.setdefault("GIT_COMMITTER_NAME", "harness")
49
+ env.setdefault("GIT_COMMITTER_EMAIL", "harness@example.invalid")
50
+ proc = subprocess.run(
51
+ cmd, cwd=str(cwd), capture_output=True, text=True, encoding="utf-8", env=env
52
+ )
53
+ if check and proc.returncode != 0:
54
+ raise RuntimeError(
55
+ "command failed (%d): %s\n%s\n%s"
56
+ % (proc.returncode, " ".join(cmd), proc.stdout[-4000:], proc.stderr[-4000:])
57
+ )
58
+ return proc
59
+
60
+
61
+ def git(args, cwd, check=True):
62
+ return run(["git"] + GIT_FLAGS + args, cwd, check=check)
63
+
64
+
65
+ def write_snapshot(files, dest):
66
+ for rel, content in files.items():
67
+ path = dest / rel
68
+ path.parent.mkdir(parents=True, exist_ok=True)
69
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
70
+ handle.write(content)
71
+
72
+
73
+ def apply_patch(patch_text, work, tmp, label):
74
+ """Apply a unified diff; return (ok, message)."""
75
+ if not patch_text or not patch_text.strip():
76
+ return False, "empty patch"
77
+ patch_file = Path(tmp) / (label + ".patch")
78
+ patch_file.write_text(patch_text, encoding="utf-8", newline="\n")
79
+ first = git(["apply", "--check", str(patch_file)], work, check=False)
80
+ if first.returncode == 0:
81
+ git(["apply", str(patch_file)], work)
82
+ return True, "applied"
83
+ second = git(["apply", "--check", "--recount", "-C1", str(patch_file)], work, check=False)
84
+ if second.returncode == 0:
85
+ git(["apply", "--recount", "-C1", str(patch_file)], work)
86
+ return True, "applied (recount)"
87
+ return False, (first.stderr or first.stdout).strip().splitlines()[0:3]
88
+
89
+
90
+ def run_tests(work, test_files, cmd_template):
91
+ cmd = [sys.executable, "-m", "pytest", "-v", "--tb=no", "-p", "no:cacheprovider"]
92
+ cmd += list(test_files)
93
+ proc = run(cmd, work, check=False)
94
+ outcomes = {}
95
+ for raw in proc.stdout.splitlines():
96
+ match = RESULT_RE.match(raw.strip())
97
+ if match:
98
+ outcomes[match.group(1)] = match.group(2)
99
+ return outcomes, proc
100
+
101
+
102
+ def evaluate(row, model_patch):
103
+ test_files = row["dockerless"]["test_files"]
104
+ f2p = json.loads(row["FAIL_TO_PASS"])
105
+ p2p = json.loads(row["PASS_TO_PASS"])
106
+
107
+ with tempfile.TemporaryDirectory(prefix="swedl-eval-") as tmp:
108
+ work = Path(tmp) / "work"
109
+ work.mkdir()
110
+ write_snapshot(row["dockerless"]["files"], work)
111
+ git(["init", "-q", "-b", "main"], work)
112
+ git(["add", "-A"], work)
113
+ git(["commit", "-q", "-m", row["base_commit"]], work)
114
+
115
+ ok, message = apply_patch(row["test_patch"], work, tmp, "test")
116
+ if not ok:
117
+ return {
118
+ "instance_id": row["instance_id"],
119
+ "resolved": False,
120
+ "reason": "test_patch failed to apply: %s" % (message,),
121
+ "f2p_passed": 0,
122
+ "f2p_total": len(f2p),
123
+ "p2p_passed": 0,
124
+ "p2p_total": len(p2p),
125
+ }
126
+
127
+ ok, message = apply_patch(model_patch, work, tmp, "model")
128
+ if not ok:
129
+ return {
130
+ "instance_id": row["instance_id"],
131
+ "resolved": False,
132
+ "reason": "model patch failed to apply: %s" % (message,),
133
+ "f2p_passed": 0,
134
+ "f2p_total": len(f2p),
135
+ "p2p_passed": 0,
136
+ "p2p_total": len(p2p),
137
+ }
138
+
139
+ outcomes, proc = run_tests(work, test_files, row["dockerless"]["test_cmd"])
140
+
141
+ if not outcomes:
142
+ return {
143
+ "instance_id": row["instance_id"],
144
+ "resolved": False,
145
+ "reason": "no tests collected (collection error?)",
146
+ "f2p_passed": 0,
147
+ "f2p_total": len(f2p),
148
+ "p2p_passed": 0,
149
+ "p2p_total": len(p2p),
150
+ }
151
+
152
+ f2p_pass = [t for t in f2p if outcomes.get(t) == "PASSED"]
153
+ p2p_pass = [t for t in p2p if outcomes.get(t) == "PASSED"]
154
+ resolved = len(f2p_pass) == len(f2p) and len(p2p_pass) == len(p2p)
155
+ failing = sorted(t for t in f2p + p2p if outcomes.get(t) != "PASSED")
156
+ return {
157
+ "instance_id": row["instance_id"],
158
+ "resolved": resolved,
159
+ "reason": "ok" if resolved else "unmet tests: %d" % (len(failing),),
160
+ "f2p_passed": len(f2p_pass),
161
+ "f2p_total": len(f2p),
162
+ "p2p_passed": len(p2p_pass),
163
+ "p2p_total": len(p2p),
164
+ "failing": failing[:12],
165
+ }
166
+
167
+
168
+ def load_predictions(path):
169
+ predictions = {}
170
+ with open(path, encoding="utf-8") as handle:
171
+ for line in handle:
172
+ line = line.strip()
173
+ if not line:
174
+ continue
175
+ record = json.loads(line)
176
+ predictions[record["instance_id"]] = (
177
+ record.get("model_patch") or record.get("patch") or ""
178
+ )
179
+ return predictions
180
+
181
+
182
+ def main():
183
+ parser = argparse.ArgumentParser(description=__doc__)
184
+ parser.add_argument("--dataset", default="SWE-DockerLess.jsonl")
185
+ parser.add_argument("--predictions", help="JSONL of {instance_id, model_patch}")
186
+ parser.add_argument("--gold", action="store_true", help="score the gold patches")
187
+ parser.add_argument("--out", help="write a JSON report here")
188
+ args = parser.parse_args()
189
+
190
+ rows = [json.loads(line) for line in open(args.dataset, encoding="utf-8") if line.strip()]
191
+
192
+ if args.gold:
193
+ predictions = {row["instance_id"]: row["patch"] for row in rows}
194
+ elif args.predictions:
195
+ predictions = load_predictions(args.predictions)
196
+ else:
197
+ parser.error("pass --gold or --predictions")
198
+
199
+ started = time.time()
200
+ results = []
201
+ print("%-22s %-9s %-7s %-7s %s" % ("instance", "resolved", "F2P", "P2P", "note"))
202
+ for row in rows:
203
+ result = evaluate(row, predictions.get(row["instance_id"], ""))
204
+ results.append(result)
205
+ print(
206
+ "%-22s %-9s %d/%-5d %d/%-5d %s"
207
+ % (
208
+ result["instance_id"],
209
+ "yes" if result["resolved"] else "no",
210
+ result["f2p_passed"],
211
+ result["f2p_total"],
212
+ result["p2p_passed"],
213
+ result["p2p_total"],
214
+ result["reason"],
215
+ )
216
+ )
217
+
218
+ resolved = sum(1 for result in results if result["resolved"])
219
+ elapsed = time.time() - started
220
+ summary = {
221
+ "dataset": str(Path(args.dataset).name),
222
+ "instances": len(rows),
223
+ "resolved": resolved,
224
+ "resolve_rate": round(resolved / len(rows), 4) if rows else 0.0,
225
+ "seconds": round(elapsed, 2),
226
+ "results": results,
227
+ }
228
+ print(
229
+ "\nresolved %d/%d (%.1f%%) in %.1fs"
230
+ % (resolved, len(rows), 100.0 * summary["resolve_rate"], elapsed)
231
+ )
232
+ if args.out:
233
+ Path(args.out).write_text(json.dumps(summary, indent=2), encoding="utf-8")
234
+ print("report -> %s" % args.out)
235
+
236
+
237
+ if __name__ == "__main__":
238
+ main()
tools/make_controls.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate negative-control prediction files for SWE-DockerLess.
2
+
3
+ Three controls, each of which must score 0/4:
4
+
5
+ empty.jsonl every prediction is an empty patch
6
+ cross.jsonl each instance receives another instance's gold patch
7
+ partial.jsonl a plausible but incomplete fix: the gold patch with one of the
8
+ bugs reintroduced (or, for semverlite, only one of its two
9
+ files fixed)
10
+
11
+ Run with: python tools/make_controls.py
12
+ """
13
+
14
+ import json
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+ REPOS = ROOT / "repos"
23
+ FIXED = ROOT / "fixed"
24
+ OUTDIR = ROOT / "predictions"
25
+ DATASET = ROOT / "SWE-DockerLess.jsonl"
26
+
27
+ GIT_FLAGS = [
28
+ "-c", "core.autocrlf=false",
29
+ "-c", "core.safecrlf=false",
30
+ "-c", "user.name=control",
31
+ "-c", "user.email=control@example.invalid",
32
+ "-c", "commit.gpgsign=false",
33
+ ]
34
+
35
+
36
+ def git(args, cwd):
37
+ proc = subprocess.run(
38
+ ["git"] + GIT_FLAGS + args, cwd=str(cwd), capture_output=True, text=True, encoding="utf-8"
39
+ )
40
+ if proc.returncode != 0:
41
+ raise RuntimeError("git %s failed: %s %s" % (args, proc.stdout, proc.stderr))
42
+ return proc
43
+
44
+
45
+ def read_tree(root):
46
+ files = {}
47
+ for path in sorted(Path(root).rglob("*")):
48
+ if path.is_dir() or ".git" in path.parts:
49
+ continue
50
+ files[path.relative_to(root).as_posix()] = path.read_text(encoding="utf-8")
51
+ return files
52
+
53
+
54
+ def write_tree(files, dest):
55
+ for rel, content in files.items():
56
+ path = Path(dest) / rel
57
+ path.parent.mkdir(parents=True, exist_ok=True)
58
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
59
+ handle.write(content)
60
+
61
+
62
+ def diff_with_overrides(name, overrides):
63
+ """Return a unified diff that turns the base repo into base+overrides."""
64
+ with tempfile.TemporaryDirectory(prefix="swedl-ctl-") as tmp:
65
+ work = Path(tmp) / "w"
66
+ work.mkdir()
67
+ write_tree(read_tree(REPOS / name), work)
68
+ git(["init", "-q", "-b", "main"], work)
69
+ git(["add", "-A"], work)
70
+ git(["commit", "-q", "-m", "base"], work)
71
+ write_tree(overrides, work)
72
+ return git(["diff", "--no-color"], work).stdout
73
+
74
+
75
+ def main():
76
+ OUTDIR.mkdir(exist_ok=True)
77
+ rows = [json.loads(line) for line in open(DATASET, encoding="utf-8") if line.strip()]
78
+ ids = [row["instance_id"] for row in rows]
79
+
80
+ # --- control 1: empty patches ----------------------------------------
81
+ with open(OUTDIR / "empty.jsonl", "w", encoding="utf-8", newline="\n") as handle:
82
+ for row in rows:
83
+ handle.write(
84
+ json.dumps(
85
+ {
86
+ "instance_id": row["instance_id"],
87
+ "model_name_or_path": "control-empty",
88
+ "model_patch": "",
89
+ }
90
+ )
91
+ + "\n"
92
+ )
93
+
94
+ # --- control 2: cross-instance gold patches ---------------------------
95
+ with open(OUTDIR / "cross.jsonl", "w", encoding="utf-8", newline="\n") as handle:
96
+ for index, row in enumerate(rows):
97
+ other = rows[(index + 1) % len(rows)]
98
+ handle.write(
99
+ json.dumps(
100
+ {
101
+ "instance_id": row["instance_id"],
102
+ "model_name_or_path": "control-cross",
103
+ "model_patch": other["patch"],
104
+ }
105
+ )
106
+ + "\n"
107
+ )
108
+
109
+ # --- control 3: plausible but incomplete fixes ------------------------
110
+ partial = {}
111
+
112
+ # miniconf: cycle detection kept, but the $$ escape dropped again
113
+ config = read_tree(FIXED / "miniconf")["miniconf/config.py"]
114
+ broken_escape = config.replace(
115
+ ' if text.startswith("$$", index):\n'
116
+ ' out.append("$")\n'
117
+ " index += 2\n"
118
+ " continue\n",
119
+ "",
120
+ )
121
+ assert broken_escape != config, "miniconf control replacement did not apply"
122
+ partial["swedl__miniconf-1"] = diff_with_overrides(
123
+ "miniconf", {"miniconf/config.py": broken_escape}
124
+ )
125
+
126
+ # ttlcache: len() fixed, but reads still do not refresh recency
127
+ cache = read_tree(FIXED / "ttlcache")["ttlcache/cache.py"]
128
+ broken_recency = cache.replace(" self._data.move_to_end(key)\n", "")
129
+ assert broken_recency != cache, "ttlcache control replacement did not apply"
130
+ partial["swedl__ttlcache-1"] = diff_with_overrides(
131
+ "ttlcache", {"ttlcache/cache.py": broken_recency}
132
+ )
133
+
134
+ # cronlite: Sunday alias fixed, but `<value>/<step>` still collapses
135
+ fields = read_tree(FIXED / "cronlite")["cronlite/fields.py"]
136
+ broken_step = fields.replace(
137
+ " start = self._check(int(base))\n stop = self.maximum\n",
138
+ " start = self._check(int(base))\n stop = start\n",
139
+ )
140
+ assert broken_step != fields, "cronlite control replacement did not apply"
141
+ partial["swedl__cronlite-1"] = diff_with_overrides(
142
+ "cronlite", {"cronlite/fields.py": broken_step}
143
+ )
144
+
145
+ # semverlite: precedence fixed, range gating left out
146
+ version = read_tree(FIXED / "semverlite")["semverlite/version.py"]
147
+ partial["swedl__semverlite-1"] = diff_with_overrides(
148
+ "semverlite", {"semverlite/version.py": version}
149
+ )
150
+
151
+ with open(OUTDIR / "partial.jsonl", "w", encoding="utf-8", newline="\n") as handle:
152
+ for instance_id in ids:
153
+ handle.write(
154
+ json.dumps(
155
+ {
156
+ "instance_id": instance_id,
157
+ "model_name_or_path": "control-partial",
158
+ "model_patch": partial[instance_id],
159
+ }
160
+ )
161
+ + "\n"
162
+ )
163
+
164
+ print("wrote controls for %d instances -> %s" % (len(ids), OUTDIR))
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
tools/validate.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structural validation for SWE-DockerLess.jsonl.
2
+
3
+ Checks that every row is SWE-bench shaped, that the two patches apply to the
4
+ embedded snapshot, that they touch disjoint files, and that the gold patch stays
5
+ inside a budget a 2048-token completion can produce.
6
+
7
+ Run with: python tools/validate.py
8
+ """
9
+
10
+ import json
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ ROOT = Path(__file__).resolve().parent.parent
17
+ DATASET = ROOT / "SWE-DockerLess.jsonl"
18
+
19
+ SWE_BENCH_FIELDS = [
20
+ "instance_id",
21
+ "repo",
22
+ "base_commit",
23
+ "patch",
24
+ "test_patch",
25
+ "problem_statement",
26
+ "hints_text",
27
+ "created_at",
28
+ "version",
29
+ "environment_setup_commit",
30
+ "FAIL_TO_PASS",
31
+ "PASS_TO_PASS",
32
+ ]
33
+
34
+ MAX_PROBLEM_CHARS = 4000
35
+ MAX_GOLD_ADDED_LINES = 120
36
+
37
+ failures = []
38
+
39
+
40
+ def check(condition, message):
41
+ if not condition:
42
+ failures.append(message)
43
+
44
+
45
+ def write_tree(files, dest):
46
+ for rel, content in files.items():
47
+ path = dest / rel
48
+ path.parent.mkdir(parents=True, exist_ok=True)
49
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
50
+ handle.write(content)
51
+
52
+
53
+ def git(args, cwd):
54
+ return subprocess.run(
55
+ [
56
+ "git",
57
+ "-c", "core.autocrlf=false",
58
+ "-c", "user.name=v",
59
+ "-c", "user.email=v@example.invalid",
60
+ ]
61
+ + args,
62
+ cwd=str(cwd),
63
+ capture_output=True,
64
+ text=True,
65
+ encoding="utf-8",
66
+ )
67
+
68
+
69
+ def touched_paths(patch):
70
+ paths = set()
71
+ for line in patch.splitlines():
72
+ if line.startswith("+++ b/") or line.startswith("--- a/"):
73
+ paths.add(line[6:])
74
+ elif line.startswith("+++ ") or line.startswith("--- "):
75
+ value = line[4:].strip()
76
+ if value != "/dev/null":
77
+ paths.add(value.split("/", 1)[-1])
78
+ return paths
79
+
80
+
81
+ def added_lines(patch):
82
+ return sum(1 for line in patch.splitlines() if line.startswith("+") and not line.startswith("+++"))
83
+
84
+
85
+ def main():
86
+ rows = [json.loads(line) for line in open(DATASET, encoding="utf-8") if line.strip()]
87
+ check(len(rows) == 4, "expected 4 rows, found %d" % len(rows))
88
+
89
+ seen = set()
90
+ for row in rows:
91
+ iid = row.get("instance_id", "<missing>")
92
+ for field in SWE_BENCH_FIELDS:
93
+ check(field in row, "%s: missing field %s" % (iid, field))
94
+ check(iid not in seen, "%s: duplicate instance_id" % iid)
95
+ seen.add(iid)
96
+
97
+ check(isinstance(row["FAIL_TO_PASS"], str), "%s: FAIL_TO_PASS must be a JSON string" % iid)
98
+ check(isinstance(row["PASS_TO_PASS"], str), "%s: PASS_TO_PASS must be a JSON string" % iid)
99
+ f2p = json.loads(row["FAIL_TO_PASS"])
100
+ p2p = json.loads(row["PASS_TO_PASS"])
101
+ check(len(f2p) >= 1, "%s: empty FAIL_TO_PASS" % iid)
102
+ check(len(p2p) >= 1, "%s: empty PASS_TO_PASS" % iid)
103
+ check(not (set(f2p) & set(p2p)), "%s: F2P/P2P overlap" % iid)
104
+ check(len(row["base_commit"]) == 40, "%s: base_commit is not a 40-char sha" % iid)
105
+
106
+ problem = row["problem_statement"]
107
+ check(len(problem) <= MAX_PROBLEM_CHARS, "%s: problem statement too long" % iid)
108
+ for test_id in f2p + p2p:
109
+ check("::" not in problem, "%s: problem statement leaks a test id" % iid)
110
+
111
+ gold_paths = touched_paths(row["patch"])
112
+ test_paths = touched_paths(row["test_patch"])
113
+ check(not (gold_paths & test_paths), "%s: patch and test_patch touch the same files" % iid)
114
+ check(
115
+ all(not path.startswith("tests/") for path in gold_paths),
116
+ "%s: gold patch edits test files" % iid,
117
+ )
118
+ check(
119
+ all(path.startswith("tests/") for path in test_paths),
120
+ "%s: test_patch edits non-test files" % iid,
121
+ )
122
+ check(
123
+ added_lines(row["patch"]) <= MAX_GOLD_ADDED_LINES,
124
+ "%s: gold patch adds %d lines (budget %d)"
125
+ % (iid, added_lines(row["patch"]), MAX_GOLD_ADDED_LINES),
126
+ )
127
+
128
+ files = row["dockerless"]["files"]
129
+ check(bool(files), "%s: empty snapshot" % iid)
130
+
131
+ with tempfile.TemporaryDirectory(prefix="swedl-val-") as tmp:
132
+ work = Path(tmp) / "w"
133
+ work.mkdir()
134
+ write_tree(files, work)
135
+ git(["init", "-q", "-b", "main"], work)
136
+ git(["add", "-A"], work)
137
+ git(["commit", "-q", "-m", "base"], work)
138
+
139
+ for label, patch_text in (("test_patch", row["test_patch"]), ("patch", row["patch"])):
140
+ patch_file = Path(tmp) / (label + ".patch")
141
+ patch_file.write_text(patch_text, encoding="utf-8", newline="\n")
142
+ result = git(["apply", "--check", str(patch_file)], work)
143
+ check(
144
+ result.returncode == 0,
145
+ "%s: %s does not apply (%s)" % (iid, label, result.stderr.strip()[:200]),
146
+ )
147
+ if label == "test_patch":
148
+ git(["apply", str(patch_file)], work)
149
+
150
+ print(
151
+ "%-22s fields=ok F2P=%-2d P2P=%-2d +%-3d lines problem=%d chars files=%d"
152
+ % (
153
+ iid,
154
+ len(f2p),
155
+ len(p2p),
156
+ added_lines(row["patch"]),
157
+ len(problem),
158
+ len(files),
159
+ )
160
+ )
161
+
162
+ total_tests = sum(len(json.loads(row["FAIL_TO_PASS"])) for row in rows)
163
+ print("\n%d instances, %d FAIL_TO_PASS tests total" % (len(rows), total_tests))
164
+ if failures:
165
+ print("\nFAILED %d checks:" % len(failures))
166
+ for message in failures:
167
+ print(" - %s" % message)
168
+ return 1
169
+ print("all checks passed")
170
+ return 0
171
+
172
+
173
+ if __name__ == "__main__":
174
+ sys.exit(main())