ilintar commited on
Commit
9368cc4
·
verified ·
1 Parent(s): fec0c33

Add corpus source: base repos, task overlays, hidden tests, and the authoring tools

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. source/CALIBRATION.md +269 -0
  2. source/README.md +71 -0
  3. source/corpus/python/ledger/repo/README.md +33 -0
  4. source/corpus/python/ledger/repo/ledger/__init__.py +13 -0
  5. source/corpus/python/ledger/repo/ledger/errors.py +28 -0
  6. source/corpus/python/ledger/repo/ledger/events.py +51 -0
  7. source/corpus/python/ledger/repo/ledger/policies.py +85 -0
  8. source/corpus/python/ledger/repo/ledger/projections.py +125 -0
  9. source/corpus/python/ledger/repo/ledger/store.py +95 -0
  10. source/corpus/python/ledger/tasks/allocate-mutates/break/ledger/policies.py +86 -0
  11. source/corpus/python/ledger/tasks/allocate-mutates/task.json +6 -0
  12. source/corpus/python/ledger/tasks/allocate-mutates/tests/test_allocate.py +41 -0
  13. source/corpus/python/ledger/tasks/audit-findings/break/ledger/policies.py +85 -0
  14. source/corpus/python/ledger/tasks/audit-findings/break/ledger/projections.py +125 -0
  15. source/corpus/python/ledger/tasks/audit-findings/break/ledger/store.py +95 -0
  16. source/corpus/python/ledger/tasks/audit-findings/task.json +7 -0
  17. source/corpus/python/ledger/tasks/audit-findings/tests/test_catch_up.py +56 -0
  18. source/corpus/python/ledger/tasks/audit-findings/tests/test_reorder.py +42 -0
  19. source/corpus/python/ledger/tasks/audit-findings/tests/test_valuation.py +64 -0
  20. source/corpus/python/ledger/tasks/audit2-01/break/ledger/policies.py +86 -0
  21. source/corpus/python/ledger/tasks/audit2-01/break/ledger/store.py +95 -0
  22. source/corpus/python/ledger/tasks/audit2-01/task.json +11 -0
  23. source/corpus/python/ledger/tasks/audit2-01/tests/test_allocate.py +41 -0
  24. source/corpus/python/ledger/tasks/audit2-01/tests/test_between.py +41 -0
  25. source/corpus/python/ledger/tasks/audit2-02/break/ledger/policies.py +86 -0
  26. source/corpus/python/ledger/tasks/audit2-02/break/ledger/projections.py +112 -0
  27. source/corpus/python/ledger/tasks/audit2-02/task.json +11 -0
  28. source/corpus/python/ledger/tasks/audit2-02/tests/test_allocate.py +41 -0
  29. source/corpus/python/ledger/tasks/audit2-02/tests/test_valuation.py +64 -0
  30. source/corpus/python/ledger/tasks/audit2-03/break/ledger/policies.py +86 -0
  31. source/corpus/python/ledger/tasks/audit2-03/break/ledger/projections.py +112 -0
  32. source/corpus/python/ledger/tasks/audit2-03/break/ledger/store.py +95 -0
  33. source/corpus/python/ledger/tasks/audit2-03/task.json +11 -0
  34. source/corpus/python/ledger/tasks/audit2-03/tests/test_allocate.py +41 -0
  35. source/corpus/python/ledger/tasks/audit2-03/tests/test_between.py +41 -0
  36. source/corpus/python/ledger/tasks/audit2-03/tests/test_catch_up.py +56 -0
  37. source/corpus/python/ledger/tasks/audit2-03/tests/test_valuation.py +64 -0
  38. source/corpus/python/ledger/tasks/audit2-04/break/ledger/policies.py +85 -0
  39. source/corpus/python/ledger/tasks/audit2-04/break/ledger/projections.py +112 -0
  40. source/corpus/python/ledger/tasks/audit2-04/break/ledger/store.py +95 -0
  41. source/corpus/python/ledger/tasks/audit2-04/task.json +11 -0
  42. source/corpus/python/ledger/tasks/audit2-04/tests/test_between.py +41 -0
  43. source/corpus/python/ledger/tasks/audit2-04/tests/test_catch_up.py +56 -0
  44. source/corpus/python/ledger/tasks/audit2-04/tests/test_imports.py +24 -0
  45. source/corpus/python/ledger/tasks/audit2-04/tests/test_valuation.py +64 -0
  46. source/corpus/python/ledger/tasks/audit2-05/break/ledger/policies.py +85 -0
  47. source/corpus/python/ledger/tasks/audit2-05/break/ledger/store.py +95 -0
  48. source/corpus/python/ledger/tasks/audit2-05/task.json +11 -0
  49. source/corpus/python/ledger/tasks/audit2-05/tests/test_between.py +41 -0
  50. source/corpus/python/ledger/tasks/audit2-05/tests/test_catch_up.py +56 -0
source/CALIBRATION.md ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agentic corpus calibration log
2
+
3
+ Target: Qwen3.5-4B resolves 15-20%. Measured after each corpus revision.
4
+
5
+ | revision | tasks | resolved | peak ctx | cumulative |
6
+ |---|---|---|---|---|
7
+ | v1 `ledger` (417 lines) | 6 | 83% | 3-6k | 9-26k |
8
+ | v2 `flow` (989 lines) | 4 | 50% | 6-17k | 27-60k |
9
+ | v3 `flow` symptom-only + multi-file | 4 | 75% | 6-13k | 26-62k |
10
+
11
+ ## What actually controls difficulty
12
+
13
+ **The fix being structural, not a token flip.** This dominates everything else.
14
+ Of the 17 tasks authored so far, ~14 are repaired by changing one operator or
15
+ one identifier, and the 4B resolves those at 50-83% regardless of how vaguely
16
+ the instruction is worded. The single task it failed -- `expr-precedence` --
17
+ requires restructuring a recursive-descent parser so `and` binds tighter than
18
+ `or`. There is no token to flip.
19
+
20
+ **Breaking several files does not force a multi-file fix.** `retry-transition-illegal`
21
+ broke `state.py` and `scheduler.py` deliberately. The model repaired it with
22
+ ONE edit, by permitting RETRYING -> RUNNING directly in the state table. That
23
+ is a legitimate fix that passes every test. Models find the minimal path; the
24
+ number of files broken is not a difficulty lever.
25
+
26
+ **Instruction vagueness helps, but only a little.** Rewriting instructions from
27
+ diagnosis ("capacity is going missing") to symptom ("the runner crashes") moved
28
+ the needle far less than expected.
29
+
30
+ ## Therefore
31
+
32
+ Author for these, in order of effect:
33
+
34
+ 1. Fixes requiring an algorithm to be understood and restructured: precedence
35
+ climbing, topological ordering, LRU recency, tie-break rules, cumulative
36
+ accounting.
37
+ 2. Bugs whose obvious local fix passes the failing test but trips a regression
38
+ guard -- the `since-inclusive` trap shape, which does work.
39
+ 3. Repo size, for peak context rather than for difficulty: localisation is not
40
+ where the 4B struggles.
41
+
42
+ Do NOT rely on: breaking multiple files, vague wording, or exotic domains.
43
+
44
+ ## Measurement round 2
45
+
46
+ | batch | tasks | resolved |
47
+ |---|---|---|
48
+ | `flow` batch 3 (symptom-only, "multi-file") | 4 | 75% |
49
+ | `router` batch (structural fixes) | 4 | 50% |
50
+
51
+ Structural-fix framing helped (75% -> 50%) but not nearly enough. Solved:
52
+ `specificity-by-sum`, `negotiate-tiebreak` -- both amount to rewriting one
53
+ comparison. Failed: `middleware-reentrancy` (a dropped guard must be
54
+ reintroduced) and `lru-recency-on-read` (the model made no edit at all).
55
+
56
+ ## The arithmetic problem
57
+
58
+ A 60-task corpus at 15-20% means only 9-12 tasks may be solvable. Tasks written
59
+ one-defect-at-a-time land around 50% solvable, so roughly 80% of the corpus has
60
+ to be out of reach. That cannot be reached by making individual bugs subtler --
61
+ it needs a difficulty dial that compounds.
62
+
63
+ ## The dial: independent compound defects
64
+
65
+ One task, two or three genuinely separate faults, each with its own failing
66
+ test, where no single edit repairs more than one. Independent probabilities
67
+ multiply: two 50% sub-defects give ~25%, three give ~12%.
68
+
69
+ Properties that make this the right dial:
70
+
71
+ * **Fair.** Every sub-defect is individually findable by reading the code. No
72
+ guessing, no trick.
73
+ * **Realistic.** Real reports frequently have several contributing causes.
74
+ * **Tunable.** Difficulty is set by the number of sub-defects, measured rather
75
+ than guessed.
76
+ * **It actually forces breadth**, unlike breaking several files, which
77
+ `retry-transition-illegal` showed a model can defeat with one legal edit.
78
+
79
+ Each sub-defect must be covered by its own fail_to_pass test, so partial credit
80
+ still reports honestly how far a model got.
81
+
82
+ ## Measurement round 3 -- stratified sample (in progress)
83
+
84
+ Compound calibration, 3 defects each, both unresolved with honest partial credit:
85
+
86
+ | task | resolved | f2p | edits | regressions |
87
+ |---|---|---|---|---|
88
+ | scheduler-incident-triage | no | 5/9 | 3 | 0 |
89
+ | router-api-review-findings | no | 6/9 | 3 | 2 |
90
+
91
+ Early stratified-sample results:
92
+
93
+ | tier | resolved |
94
+ |---|---|
95
+ | single | 2/2 |
96
+ | 2-defect | 1/2 |
97
+
98
+ ## Sub-defect success is correlated, not independent
99
+
100
+ The dial was designed on the assumption that independent probabilities
101
+ multiply: two 50% sub-defects giving ~25%. Measurement does not support that.
102
+ Two-defect compounds are resolving near 50%, not 25% -- a model that locates
103
+ one defect in a repository it has just read tends to locate the next one too,
104
+ because the expensive part (orienting in the code) is paid once and then shared
105
+ across every defect in the same task.
106
+
107
+ So the dial is real but far weaker than modelled: each added defect costs much
108
+ less than a factor of two. Practical consequences:
109
+
110
+ * Three- and four-defect compounds are the only tiers that move the number.
111
+ * Corpus composition must lean overwhelmingly on those tiers.
112
+ * Projected rates from multiplying per-defect probabilities are not usable.
113
+ Every tier rate must be measured directly, which is what the stratified
114
+ sample is for.
115
+
116
+ ## Host repo matters as much as defect count
117
+
118
+ `ledger-audit3-02` -- three defects -- resolved completely, 15/15. Its
119
+ ingredients are fifo-lifo + import-syntax + since-inclusive, all on the 417-line
120
+ `ledger` repo, and one of them is the trivial syntax error that exists to hold
121
+ the floor off zero.
122
+
123
+ So compound difficulty is not a property of the defect count alone. A compound
124
+ inherits the difficulty of the repository it sits in, and `ledger` is small
125
+ enough to read end to end, which removes the orientation cost that makes
126
+ compounds hard elsewhere.
127
+
128
+ Consequence for composition: `ledger` is the easy tier at every defect count and
129
+ should not be used for the hard tiers. The hard tiers must come from `flow`
130
+ (989 lines) and `router` (578 lines, 12 modules). Compound tasks built on
131
+ `ledger` are retained only as part of the deliberate easy floor.
132
+
133
+ ## Repo size is the strong dial; defect count is the weak one
134
+
135
+ Stratified sample, split by host repo rather than by tier:
136
+
137
+ | tier | ledger (417 lines) | flow / router |
138
+ |---|---|---|
139
+ | single | 2/2 | 0/1 |
140
+ | 2-defect | 2/2 | 0/1 |
141
+ | 3-defect | 1/2 | pending |
142
+
143
+ A single-defect task on `flow` (`acquire-not-atomic`) went unresolved at 0/4,
144
+ while a three-defect compound on `ledger` resolved fully at 15/15. That settles
145
+ it: what makes these tasks hard is having to orient in a repository too large to
146
+ hold at once, not how many faults are hidden in it.
147
+
148
+ This inverts the assumption the previous three rounds were built on. Defect
149
+ count still helps -- it is why the hard-repo compounds are the hardest tier --
150
+ but it is a second-order effect on top of repo size.
151
+
152
+ ### Composition that follows
153
+
154
+ With easy ~80% and hard ~15%, a 60-task corpus hitting 17.5% is about 4 easy
155
+ plus 56 hard. Four solvable tasks is a deliberate, non-zero floor: a corpus
156
+ that scores a leading small model at zero discriminates no better than one that
157
+ scores it at 100%.
158
+
159
+ Available: 15 tasks on `ledger`, 83 on `flow` + `router`, so the hard tier is
160
+ not supply-constrained.
161
+
162
+ ### If a harder corpus is ever wanted
163
+
164
+ Add a repo larger than `flow`, not more defects per task. Peak context on
165
+ hard-repo episodes is already 7.3-8.9k against 4.7-5.6k on easy-repo ones,
166
+ which is the same effect showing up in the token numbers.
167
+
168
+ ## Stratified sample, 13/15 complete
169
+
170
+ | group | resolved |
171
+ |---|---|
172
+ | `ledger` (417 lines) | 7/8 = 88% |
173
+ | `flow` + `router` | 1/5 = 20% |
174
+
175
+ Hard-repo breakdown: single 1/2, two-defect 0/1, three-defect 0/2.
176
+
177
+ **Hard-repo tasks alone sit at 20%, the top of the wanted band.** So the corpus
178
+ does not need an easy tier to hold the floor -- 20% of 60 is about 12 solved,
179
+ which is already a non-zero floor -- and including `ledger` tasks would push the
180
+ aggregate above the band rather than protect it.
181
+
182
+ Composition that follows: ship ~60 tasks drawn from `flow` and `router` only,
183
+ weighted toward compounds over singles to sit mid-band rather than at the
184
+ ceiling. Roughly 8 hard singles (~50%) plus ~52 hard compounds (~10%) projects
185
+ to about 15%.
186
+
187
+ `ledger` is retained in the corpus source as the easy tier for anyone
188
+ calibrating a weaker model, but is excluded from the default 60.
189
+
190
+ ## Does the benchmark measure coding, or tool-driving?
191
+
192
+ Across all 31 measured episodes:
193
+
194
+ | signal | count |
195
+ |---|---|
196
+ | tool errors | 1 total, in 1 episode |
197
+ | malformed JSON arguments | 1 |
198
+ | path-escape attempts | 0 |
199
+ | terminated via `finish` | 23 |
200
+ | terminated at the nudge limit | 7 |
201
+ | zero-edit episodes | 5 |
202
+
203
+ Qwen3.5-4B drives the protocol essentially without error, so a failed task is a
204
+ failed *repair*, not a failed tool call. That was the main threat to the
205
+ benchmark's validity -- a small model can fail either because it cannot solve
206
+ the problem or because it cannot work the tools, and those must not be
207
+ conflated. Measurement says they are not.
208
+
209
+ Of 15 unresolved episodes, 7 made partial progress and 8 made none, so the
210
+ fail_to_pass fraction discriminates rather than collapsing to a binary.
211
+
212
+ Worth re-reading here: the *nudge* is what makes this true. Before it, a model
213
+ that narrated its analysis in prose without emitting a tool call ended the
214
+ episode with zero edits, and the suite reported a fake 0% that looked like a
215
+ hard benchmark. 7 of 31 episodes still end at the nudge limit rather than via
216
+ `finish`, so that path is exercised regularly and is not a corner case.
217
+
218
+ ## Final calibration (pooled sample + verification, hard repos only)
219
+
220
+ | tier | resolved |
221
+ |---|---|
222
+ | single | 2/3 (~67%) |
223
+ | 2-defect | 0/3 |
224
+ | 3-defect | 1/6 |
225
+ | 4-defect | 0/1 |
226
+ | **all compounds** | **1/10 (~10%)** |
227
+
228
+ Compounds are ~10%, not the 0% that the first five samples suggested -- one
229
+ three-defect router task resolved completely at 16/16. Re-projecting the shipped
230
+ mix on these rates put it at 23%, above the wanted ceiling, so the mix was
231
+ re-selected: 10 singles + 50 compounds, projecting 19.4%.
232
+
233
+ The selector could not go below 10 singles and still reach 60 tasks under the
234
+ <=5x defect-reuse cap. Fewer singles would need more compounds than the
235
+ diversity constraint allows.
236
+
237
+ **Uncertainty worth carrying:** the single rate is n=3. At 50% rather than 67%
238
+ the mix lands at 16.7%. The honest range is roughly 16-19%.
239
+
240
+ ## Diversity constraint
241
+
242
+ The corpus was reuse-limited, not task-limited. 60 tasks drawn from 29 distinct
243
+ defects meant one unfixable defect sank up to 8 tasks, so the effective number
244
+ of independent signals was ~29, and a confidence interval computed as 60
245
+ independent trials would be too narrow. Selection alone could not fix it: caps
246
+ of 4/5/6 reached only 45/51/57 tasks. Authoring 5 further distinct defects took
247
+ the pool to 36 and let the shipped 60 run at <=5x reuse over 34 distinct
248
+ defects.
249
+
250
+ Tightening reuse from 8x to 5x did not move the projected rate, so difficulty
251
+ and diversity are independent knobs here -- checked, not assumed.
252
+
253
+ ## FINAL (n=19 hard-repo episodes, pooled)
254
+
255
+ | tier | resolved |
256
+ |---|---|
257
+ | single | 3/5 = 60% |
258
+ | compound | 1/14 = 7% |
259
+ | overall | 4/19 = 21% |
260
+
261
+ Shipped mix is 10 singles + 50 compounds, which on these rates projects
262
+ **16.0%** -- mid-band on the 15-20% target.
263
+
264
+ Corpus: 60 tasks selected from 129 validated. 34 distinct defects, no defect
265
+ reused more than 5 times. 31 Python (`flow`, 989 lines) + 29 TypeScript
266
+ (`router`, 578 lines). Tokens per episode 16-134k cumulative (median ~40k),
267
+ peak context 3.8-10.7k.
268
+
269
+ Verification runs are in calib-sample.json and verify60.json.
source/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SACB — corpus source
2
+
3
+ The parquet files in this repository are the *materialised* benchmark: each
4
+ record carries a full file map, hidden tests and reference fix, which is
5
+ everything a harness needs to run SACB.
6
+
7
+ This directory is what those records were built *from*, so the corpus can be
8
+ regenerated, extended, or ported to another language.
9
+
10
+ ## Layout
11
+
12
+ ```
13
+ corpus/<lang>/<repo>/repo/ the base tree, in its CORRECT state
14
+ corpus/<lang>/<repo>/tasks/<id>/task.json metadata + the bug report
15
+ corpus/<lang>/<repo>/tasks/<id>/break/ overlay that injects the defect
16
+ corpus/<lang>/<repo>/tasks/<id>/tests/ hidden tests
17
+ corpus/<lang>/<repo>/tasks/<id>/gold/ optional; defaults to the base tree
18
+ ```
19
+
20
+ The base repository is the **correct** code and each task overlays a defect on
21
+ top of it. The reference fix is therefore the base itself, which is why a task
22
+ cannot ship with a "solution" that does not work. For add-a-feature tasks the
23
+ break overlay simply removes the implementation.
24
+
25
+ ## Tools
26
+
27
+ | script | role |
28
+ |---|---|
29
+ | `tools/build_corpus.py` | validate every task and emit the JSONL the parquet is built from |
30
+ | `tools/make_tasks.py` | helper used by the authoring scripts |
31
+ | `tools/tasks_*.py` | the authoring batches, one defect or compound per entry |
32
+ | `tools/gen_compounds.py` | compose compound tasks from validated single defects |
33
+ | `tools/select_corpus.py` | choose the shipped mix to hit a target resolved rate |
34
+ | `tools/upload_sacb.py` | publish to this repository |
35
+ | `tools/harness-tests/` | tests for the llama-eval harness itself |
36
+
37
+ These import `eval_sandbox` and `agentic_eval` from `examples/llama-eval/` in
38
+ llama.cpp, so point `sys.path` at a checkout that has them.
39
+
40
+ ## Regenerating
41
+
42
+ ```bash
43
+ python3 tools/build_corpus.py --corpus corpus --out agentic-corpus.jsonl
44
+ ```
45
+
46
+ `fail_to_pass` and `pass_to_pass` are **derived**, never written by hand: the
47
+ tests are run once against the defective tree and once against the reference,
48
+ and the sets fall out of the difference. The builder rejects a task whose defect
49
+ no test exercises, and one whose reference fix does not itself pass. It caught
50
+ several authoring mistakes that way, which is the point.
51
+
52
+ ## Adding a task
53
+
54
+ Add an entry to a `tasks_*.py` batch giving the exact anchor text to replace and
55
+ the tests, run the builder, and fix whatever it rejects. Anchors are matched
56
+ exactly and must occur exactly once, so a defect can never silently fail to be
57
+ injected.
58
+
59
+ ## Adding a language
60
+
61
+ The harness takes a new language as a `LangSpec` entry (linter argv, test
62
+ runner, packages) without any other change. Java was scoped out of this release
63
+ but needs no harness work — a JDK tarball plus the JUnit console-standalone jar
64
+ would keep the no-container property.
65
+
66
+ ## Calibration
67
+
68
+ `CALIBRATION.md` records every measurement taken while tuning this corpus, and
69
+ in particular the four assumptions about difficulty that measurement
70
+ contradicted. Read it before changing the composition — the headline is that
71
+ **repository size, not defect count, is what makes these tasks hard**.
source/corpus/python/ledger/repo/README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ledger
2
+
3
+ A small event-sourced inventory ledger.
4
+
5
+ Everything that happens to stock is recorded as an immutable event in the
6
+ `EventStore`. Current state is never stored directly; it is derived by folding
7
+ the event log through a *projection*.
8
+
9
+ from ledger import EventStore, StockProjection
10
+
11
+ store = EventStore()
12
+ store.receive("widget", qty=100, unit_cost=2.50)
13
+ store.ship("widget", qty=30)
14
+
15
+ stock = StockProjection()
16
+ stock.catch_up(store)
17
+ stock.on_hand("widget") # 70
18
+
19
+ ## Layout
20
+
21
+ | module | role |
22
+ |---|---|
23
+ | `events.py` | immutable event types |
24
+ | `store.py` | append-only log, owns sequence numbering |
25
+ | `projections.py` | `StockProjection` (units) and `Valuation` (FIFO cost) |
26
+ | `policies.py` | reorder suggestions and multi-warehouse allocation |
27
+ | `errors.py` | exception hierarchy |
28
+
29
+ ## Resuming a projection
30
+
31
+ Projections are incremental. Each remembers the last sequence number it
32
+ applied and asks the store only for events after it, so catching up a long
33
+ ledger does not mean replaying it from the beginning.
source/corpus/python/ledger/repo/ledger/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A small event-sourced inventory ledger."""
2
+ from .errors import LedgerError, UnknownSku, InsufficientStock
3
+ from .events import Event, Received, Shipped, Adjusted
4
+ from .store import EventStore
5
+ from .projections import StockProjection, Valuation
6
+ from .policies import ReorderPolicy, allocate
7
+
8
+ __all__ = [
9
+ "LedgerError", "UnknownSku", "InsufficientStock",
10
+ "Event", "Received", "Shipped", "Adjusted",
11
+ "EventStore", "StockProjection", "Valuation",
12
+ "ReorderPolicy", "allocate",
13
+ ]
source/corpus/python/ledger/repo/ledger/errors.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exception types raised across the ledger."""
2
+
3
+
4
+ class LedgerError(Exception):
5
+ """Base class for every error this package raises."""
6
+
7
+
8
+ class UnknownSku(LedgerError):
9
+ """A SKU was referenced that the ledger has never seen."""
10
+
11
+ def __init__(self, sku: str):
12
+ super().__init__(f"unknown sku: {sku}")
13
+ self.sku = sku
14
+
15
+
16
+ class InsufficientStock(LedgerError):
17
+ """A shipment was requested for more units than are on hand."""
18
+
19
+ def __init__(self, sku: str, wanted: int, available: int):
20
+ super().__init__(
21
+ f"cannot ship {wanted} of {sku}: only {available} on hand")
22
+ self.sku = sku
23
+ self.wanted = wanted
24
+ self.available = available
25
+
26
+
27
+ class SequenceError(LedgerError):
28
+ """Events were presented to a projection out of order."""
source/corpus/python/ledger/repo/ledger/events.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event types.
2
+
3
+ Every event carries a monotonically increasing sequence number assigned by the
4
+ store, plus the SKU it concerns. Events are immutable once created: a ledger
5
+ that can be rewritten after the fact is not a ledger.
6
+ """
7
+ from dataclasses import dataclass
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Event:
12
+ """Base event. `seq` is assigned by the store, never by the caller."""
13
+ seq: int
14
+ ts: float
15
+ sku: str
16
+
17
+ @property
18
+ def kind(self) -> str:
19
+ return type(self).__name__.lower()
20
+
21
+ def describe(self) -> str:
22
+ return f"[{self.seq}] {self.kind} {self.sku}"
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Received(Event):
27
+ """Stock arrived into the warehouse at a known unit cost."""
28
+ qty: int
29
+ unit_cost: float
30
+
31
+ def describe(self) -> str:
32
+ return f"{super().describe()} +{self.qty} @ {self.unit_cost:.2f}"
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Shipped(Event):
37
+ """Stock left the warehouse."""
38
+ qty: int
39
+
40
+ def describe(self) -> str:
41
+ return f"{super().describe()} -{self.qty}"
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Adjusted(Event):
46
+ """A stocktake correction. `delta` may be negative."""
47
+ delta: int
48
+ reason: str
49
+
50
+ def describe(self) -> str:
51
+ return f"{super().describe()} {self.delta:+d} ({self.reason})"
source/corpus/python/ledger/repo/ledger/policies.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]:
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = sorted(warehouses, key=lambda w: (-w.priority, w.name))
72
+ available = sum(w.on_hand for w in ordered)
73
+ if available < demand:
74
+ raise InsufficientStock("<multiple>", demand, available)
75
+
76
+ plan: List[Tuple[str, int]] = []
77
+ remaining = demand
78
+ for warehouse in ordered:
79
+ if remaining <= 0:
80
+ break
81
+ take = min(warehouse.on_hand, remaining)
82
+ if take > 0:
83
+ plan.append((warehouse.name, take))
84
+ remaining -= take
85
+ return plan
source/corpus/python/ledger/repo/ledger/projections.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read models built by folding the event log.
2
+
3
+ A projection is resumable: it remembers the last sequence number it applied
4
+ and asks the store only for what came after. That is what keeps a long ledger
5
+ cheap to query, and it is why the store's `since` boundary matters so much.
6
+ """
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, List, Optional, Tuple
9
+
10
+ from .errors import SequenceError, UnknownSku
11
+ from .events import Adjusted, Event, Received, Shipped
12
+ from .store import EventStore
13
+
14
+
15
+ class StockProjection:
16
+ """Units on hand per SKU."""
17
+
18
+ def __init__(self) -> None:
19
+ self.levels: Dict[str, int] = {}
20
+ self.last_seq: int = 0
21
+
22
+ def apply(self, event: Event) -> None:
23
+ """Fold a single event into the running totals."""
24
+ if event.seq <= self.last_seq:
25
+ raise SequenceError(
26
+ f"event {event.seq} already applied (at {self.last_seq})")
27
+ current = self.levels.get(event.sku, 0)
28
+ if isinstance(event, Received):
29
+ current += event.qty
30
+ elif isinstance(event, Shipped):
31
+ current -= event.qty
32
+ elif isinstance(event, Adjusted):
33
+ current += event.delta
34
+ self.levels[event.sku] = current
35
+ self.last_seq = event.seq
36
+
37
+ def catch_up(self, store: EventStore) -> int:
38
+ """Apply everything appended since the last call. Returns the count."""
39
+ pending = store.since(self.last_seq)
40
+ for event in pending:
41
+ self.apply(event)
42
+ return len(pending)
43
+
44
+ def on_hand(self, sku: str) -> int:
45
+ if sku not in self.levels:
46
+ raise UnknownSku(sku)
47
+ return self.levels[sku]
48
+
49
+ def negative_skus(self) -> List[str]:
50
+ """SKUs the log says we hold a negative quantity of."""
51
+ return sorted(s for s, n in self.levels.items() if n < 0)
52
+
53
+
54
+ @dataclass
55
+ class Lot:
56
+ """One receipt still carrying unconsumed units."""
57
+ seq: int
58
+ qty: int
59
+ unit_cost: float
60
+
61
+
62
+ class Valuation:
63
+ """Inventory value under first-in, first-out cost basis."""
64
+
65
+ def __init__(self) -> None:
66
+ self.lots: Dict[str, List[Lot]] = {}
67
+ self.last_seq: int = 0
68
+ self.cost_of_goods_sold: float = 0.0
69
+
70
+ def apply(self, event: Event) -> None:
71
+ lots = self.lots.setdefault(event.sku, [])
72
+ if isinstance(event, Received):
73
+ lots.append(Lot(seq=event.seq, qty=event.qty,
74
+ unit_cost=event.unit_cost))
75
+ elif isinstance(event, Shipped):
76
+ self._consume(lots, event.qty)
77
+ elif isinstance(event, Adjusted):
78
+ if event.delta > 0:
79
+ unit_cost = lots[-1].unit_cost if lots else 0.0
80
+ lots.append(Lot(seq=event.seq, qty=event.delta,
81
+ unit_cost=unit_cost))
82
+ else:
83
+ self._consume(lots, -event.delta)
84
+ self.last_seq = event.seq
85
+
86
+ def _consume(self, lots: List[Lot], qty: int) -> None:
87
+ """Draw `qty` units from the oldest lots first."""
88
+ remaining = qty
89
+ while remaining > 0 and lots:
90
+ oldest = lots[0]
91
+ take = min(oldest.qty, remaining)
92
+ self.cost_of_goods_sold += take * oldest.unit_cost
93
+ oldest.qty -= take
94
+ remaining -= take
95
+ if oldest.qty == 0:
96
+ lots.pop(0)
97
+
98
+ def catch_up(self, store: EventStore) -> int:
99
+ pending = store.since(self.last_seq)
100
+ for event in pending:
101
+ self.apply(event)
102
+ return len(pending)
103
+
104
+ def value_of(self, sku: str) -> float:
105
+ """Total carrying value of the units still on hand for one SKU."""
106
+ if sku not in self.lots:
107
+ raise UnknownSku(sku)
108
+ return sum(lot.qty * lot.unit_cost for lot in self.lots[sku])
109
+
110
+ def average_cost(self, sku: str) -> float:
111
+ """Weighted average cost of the units still on hand.
112
+
113
+ Zero when nothing is on hand, rather than a division error -- callers
114
+ display this per SKU and a depleted line is normal.
115
+ """
116
+ if sku not in self.lots:
117
+ raise UnknownSku(sku)
118
+ units = sum(lot.qty for lot in self.lots[sku])
119
+ if units == 0:
120
+ return 0.0
121
+ return self.value_of(sku) / units
122
+
123
+ def total_value(self) -> float:
124
+ return sum(lot.qty * lot.unit_cost
125
+ for lots in self.lots.values() for lot in lots)
source/corpus/python/ledger/repo/ledger/store.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only event store with snapshot support.
2
+
3
+ The store owns sequence numbering. Nothing else in the package is allowed to
4
+ assign a sequence number, because the ordering guarantee that projections rely
5
+ on is only as good as the single place that hands the numbers out.
6
+ """
7
+ from typing import Dict, Iterable, Iterator, List, Optional
8
+
9
+ from .errors import SequenceError
10
+ from .events import Adjusted, Event, Received, Shipped
11
+
12
+
13
+ class EventStore:
14
+ """Holds every event ever appended, in order."""
15
+
16
+ def __init__(self) -> None:
17
+ self._events: List[Event] = []
18
+ self._next_seq: int = 1
19
+ self._clock: float = 0.0
20
+
21
+ # -- writing ---------------------------------------------------------
22
+
23
+ def _tick(self) -> float:
24
+ self._clock += 1.0
25
+ return self._clock
26
+
27
+ def _append(self, event: Event) -> Event:
28
+ if event.seq != self._next_seq:
29
+ raise SequenceError(
30
+ f"expected seq {self._next_seq}, got {event.seq}")
31
+ self._events.append(event)
32
+ self._next_seq += 1
33
+ return event
34
+
35
+ def receive(self, sku: str, qty: int, unit_cost: float) -> Received:
36
+ """Record stock arriving."""
37
+ if qty <= 0:
38
+ raise ValueError("received quantity must be positive")
39
+ return self._append(
40
+ Received(seq=self._next_seq, ts=self._tick(), sku=sku,
41
+ qty=qty, unit_cost=unit_cost))
42
+
43
+ def ship(self, sku: str, qty: int) -> Shipped:
44
+ """Record stock leaving. Does not itself check availability."""
45
+ if qty <= 0:
46
+ raise ValueError("shipped quantity must be positive")
47
+ return self._append(
48
+ Shipped(seq=self._next_seq, ts=self._tick(), sku=sku, qty=qty))
49
+
50
+ def adjust(self, sku: str, delta: int, reason: str) -> Adjusted:
51
+ """Record a stocktake correction."""
52
+ if delta == 0:
53
+ raise ValueError("adjustment delta must not be zero")
54
+ return self._append(
55
+ Adjusted(seq=self._next_seq, ts=self._tick(), sku=sku,
56
+ delta=delta, reason=reason))
57
+
58
+ # -- reading ---------------------------------------------------------
59
+
60
+ def __len__(self) -> int:
61
+ return len(self._events)
62
+
63
+ def __iter__(self) -> Iterator[Event]:
64
+ return iter(self._events)
65
+
66
+ @property
67
+ def head(self) -> int:
68
+ """Sequence number of the most recent event, or 0 when empty."""
69
+ return self._events[-1].seq if self._events else 0
70
+
71
+ def since(self, seq: int) -> List[Event]:
72
+ """Every event appended strictly after `seq`.
73
+
74
+ A projection resumes by passing the sequence number it last applied, so
75
+ this must be exclusive at the lower bound. Making it inclusive would
76
+ replay one already-applied event on every resume.
77
+ """
78
+ return [e for e in self._events if e.seq > seq]
79
+
80
+ def between(self, low: int, high: int) -> List[Event]:
81
+ """Events with low < seq <= high."""
82
+ return [e for e in self._events if low < e.seq <= high]
83
+
84
+ def for_sku(self, sku: str) -> List[Event]:
85
+ return [e for e in self._events if e.sku == sku]
86
+
87
+ def skus(self) -> List[str]:
88
+ seen: Dict[str, None] = {}
89
+ for event in self._events:
90
+ seen.setdefault(event.sku, None)
91
+ return list(seen)
92
+
93
+ def replay(self, events: Optional[Iterable[Event]] = None) -> List[Event]:
94
+ """Materialise an event iterable, defaulting to the whole log."""
95
+ return list(self._events if events is None else events)
source/corpus/python/ledger/tasks/allocate-mutates/break/ledger/policies.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]:
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = warehouses
72
+ ordered.sort(key=lambda w: (-w.priority, w.name))
73
+ available = sum(w.on_hand for w in ordered)
74
+ if available < demand:
75
+ raise InsufficientStock("<multiple>", demand, available)
76
+
77
+ plan: List[Tuple[str, int]] = []
78
+ remaining = demand
79
+ for warehouse in ordered:
80
+ if remaining <= 0:
81
+ break
82
+ take = min(warehouse.on_hand, remaining)
83
+ if take > 0:
84
+ plan.append((warehouse.name, take))
85
+ remaining -= take
86
+ return plan
source/corpus/python/ledger/tasks/allocate-mutates/task.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 3,
5
+ "instruction": "A caller that allocates twice from the same warehouse list gets a different plan the second time, and reports that their own list comes back reordered afterwards.\n\nallocate() is supposed to be free of side effects on its arguments. Fix it."
6
+ }
source/corpus/python/ledger/tasks/allocate-mutates/tests/test_allocate.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import allocate
4
+ from ledger.policies import Warehouse
5
+
6
+
7
+ def houses():
8
+ return [Warehouse("north", 1, 5),
9
+ Warehouse("south", 3, 5),
10
+ Warehouse("east", 2, 5)]
11
+
12
+
13
+ class TestAllocateIsPure(unittest.TestCase):
14
+ def test_caller_list_order_is_untouched(self):
15
+ warehouses = houses()
16
+ before = [w.name for w in warehouses]
17
+ allocate(6, warehouses)
18
+ self.assertEqual([w.name for w in warehouses], before)
19
+
20
+ def test_repeated_calls_agree(self):
21
+ warehouses = houses()
22
+ first = allocate(7, warehouses)
23
+ second = allocate(7, warehouses)
24
+ self.assertEqual(first, second)
25
+
26
+
27
+ class TestAllocateBehaviour(unittest.TestCase):
28
+ def test_highest_priority_first(self):
29
+ self.assertEqual(allocate(5, houses()), [("south", 5)])
30
+
31
+ def test_spills_into_next_priority(self):
32
+ self.assertEqual(allocate(8, houses()), [("south", 5), ("east", 3)])
33
+
34
+ def test_ties_broken_by_name(self):
35
+ tied = [Warehouse("b", 5, 2), Warehouse("a", 5, 2)]
36
+ self.assertEqual(allocate(3, tied), [("a", 2), ("b", 1)])
37
+
38
+ def test_insufficient_stock_raises(self):
39
+ from ledger.errors import InsufficientStock
40
+ with self.assertRaises(InsufficientStock):
41
+ allocate(999, houses())
source/corpus/python/ledger/tasks/audit-findings/break/ledger/policies.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]:
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level < threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = sorted(warehouses, key=lambda w: (-w.priority, w.name))
72
+ available = sum(w.on_hand for w in ordered)
73
+ if available < demand:
74
+ raise InsufficientStock("<multiple>", demand, available)
75
+
76
+ plan: List[Tuple[str, int]] = []
77
+ remaining = demand
78
+ for warehouse in ordered:
79
+ if remaining <= 0:
80
+ break
81
+ take = min(warehouse.on_hand, remaining)
82
+ if take > 0:
83
+ plan.append((warehouse.name, take))
84
+ remaining -= take
85
+ return plan
source/corpus/python/ledger/tasks/audit-findings/break/ledger/projections.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read models built by folding the event log.
2
+
3
+ A projection is resumable: it remembers the last sequence number it applied
4
+ and asks the store only for what came after. That is what keeps a long ledger
5
+ cheap to query, and it is why the store's `since` boundary matters so much.
6
+ """
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, List, Optional, Tuple
9
+
10
+ from .errors import SequenceError, UnknownSku
11
+ from .events import Adjusted, Event, Received, Shipped
12
+ from .store import EventStore
13
+
14
+
15
+ class StockProjection:
16
+ """Units on hand per SKU."""
17
+
18
+ def __init__(self) -> None:
19
+ self.levels: Dict[str, int] = {}
20
+ self.last_seq: int = 0
21
+
22
+ def apply(self, event: Event) -> None:
23
+ """Fold a single event into the running totals."""
24
+ if event.seq <= self.last_seq:
25
+ raise SequenceError(
26
+ f"event {event.seq} already applied (at {self.last_seq})")
27
+ current = self.levels.get(event.sku, 0)
28
+ if isinstance(event, Received):
29
+ current += event.qty
30
+ elif isinstance(event, Shipped):
31
+ current -= event.qty
32
+ elif isinstance(event, Adjusted):
33
+ current += event.delta
34
+ self.levels[event.sku] = current
35
+ self.last_seq = event.seq
36
+
37
+ def catch_up(self, store: EventStore) -> int:
38
+ """Apply everything appended since the last call. Returns the count."""
39
+ pending = store.since(self.last_seq)
40
+ for event in pending:
41
+ self.apply(event)
42
+ return len(pending)
43
+
44
+ def on_hand(self, sku: str) -> int:
45
+ if sku not in self.levels:
46
+ raise UnknownSku(sku)
47
+ return self.levels[sku]
48
+
49
+ def negative_skus(self) -> List[str]:
50
+ """SKUs the log says we hold a negative quantity of."""
51
+ return sorted(s for s, n in self.levels.items() if n < 0)
52
+
53
+
54
+ @dataclass
55
+ class Lot:
56
+ """One receipt still carrying unconsumed units."""
57
+ seq: int
58
+ qty: int
59
+ unit_cost: float
60
+
61
+
62
+ class Valuation:
63
+ """Inventory value under first-in, first-out cost basis."""
64
+
65
+ def __init__(self) -> None:
66
+ self.lots: Dict[str, List[Lot]] = {}
67
+ self.last_seq: int = 0
68
+ self.cost_of_goods_sold: float = 0.0
69
+
70
+ def apply(self, event: Event) -> None:
71
+ lots = self.lots.setdefault(event.sku, [])
72
+ if isinstance(event, Received):
73
+ lots.append(Lot(seq=event.seq, qty=event.qty,
74
+ unit_cost=event.unit_cost))
75
+ elif isinstance(event, Shipped):
76
+ self._consume(lots, event.qty)
77
+ elif isinstance(event, Adjusted):
78
+ if event.delta > 0:
79
+ unit_cost = lots[-1].unit_cost if lots else 0.0
80
+ lots.append(Lot(seq=event.seq, qty=event.delta,
81
+ unit_cost=unit_cost))
82
+ else:
83
+ self._consume(lots, -event.delta)
84
+ self.last_seq = event.seq
85
+
86
+ def _consume(self, lots: List[Lot], qty: int) -> None:
87
+ """Draw `qty` units from the oldest lots first."""
88
+ remaining = qty
89
+ while remaining > 0 and lots:
90
+ oldest = lots[-1]
91
+ take = min(oldest.qty, remaining)
92
+ self.cost_of_goods_sold += take * oldest.unit_cost
93
+ oldest.qty -= take
94
+ remaining -= take
95
+ if oldest.qty == 0:
96
+ lots.pop()
97
+
98
+ def catch_up(self, store: EventStore) -> int:
99
+ pending = store.since(self.last_seq)
100
+ for event in pending:
101
+ self.apply(event)
102
+ return len(pending)
103
+
104
+ def value_of(self, sku: str) -> float:
105
+ """Total carrying value of the units still on hand for one SKU."""
106
+ if sku not in self.lots:
107
+ raise UnknownSku(sku)
108
+ return sum(lot.qty * lot.unit_cost for lot in self.lots[sku])
109
+
110
+ def average_cost(self, sku: str) -> float:
111
+ """Weighted average cost of the units still on hand.
112
+
113
+ Zero when nothing is on hand, rather than a division error -- callers
114
+ display this per SKU and a depleted line is normal.
115
+ """
116
+ if sku not in self.lots:
117
+ raise UnknownSku(sku)
118
+ units = sum(lot.qty for lot in self.lots[sku])
119
+ if units == 0:
120
+ return 0.0
121
+ return self.value_of(sku) / units
122
+
123
+ def total_value(self) -> float:
124
+ return sum(lot.qty * lot.unit_cost
125
+ for lots in self.lots.values() for lot in lots)
source/corpus/python/ledger/tasks/audit-findings/break/ledger/store.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only event store with snapshot support.
2
+
3
+ The store owns sequence numbering. Nothing else in the package is allowed to
4
+ assign a sequence number, because the ordering guarantee that projections rely
5
+ on is only as good as the single place that hands the numbers out.
6
+ """
7
+ from typing import Dict, Iterable, Iterator, List, Optional
8
+
9
+ from .errors import SequenceError
10
+ from .events import Adjusted, Event, Received, Shipped
11
+
12
+
13
+ class EventStore:
14
+ """Holds every event ever appended, in order."""
15
+
16
+ def __init__(self) -> None:
17
+ self._events: List[Event] = []
18
+ self._next_seq: int = 1
19
+ self._clock: float = 0.0
20
+
21
+ # -- writing ---------------------------------------------------------
22
+
23
+ def _tick(self) -> float:
24
+ self._clock += 1.0
25
+ return self._clock
26
+
27
+ def _append(self, event: Event) -> Event:
28
+ if event.seq != self._next_seq:
29
+ raise SequenceError(
30
+ f"expected seq {self._next_seq}, got {event.seq}")
31
+ self._events.append(event)
32
+ self._next_seq += 1
33
+ return event
34
+
35
+ def receive(self, sku: str, qty: int, unit_cost: float) -> Received:
36
+ """Record stock arriving."""
37
+ if qty <= 0:
38
+ raise ValueError("received quantity must be positive")
39
+ return self._append(
40
+ Received(seq=self._next_seq, ts=self._tick(), sku=sku,
41
+ qty=qty, unit_cost=unit_cost))
42
+
43
+ def ship(self, sku: str, qty: int) -> Shipped:
44
+ """Record stock leaving. Does not itself check availability."""
45
+ if qty <= 0:
46
+ raise ValueError("shipped quantity must be positive")
47
+ return self._append(
48
+ Shipped(seq=self._next_seq, ts=self._tick(), sku=sku, qty=qty))
49
+
50
+ def adjust(self, sku: str, delta: int, reason: str) -> Adjusted:
51
+ """Record a stocktake correction."""
52
+ if delta == 0:
53
+ raise ValueError("adjustment delta must not be zero")
54
+ return self._append(
55
+ Adjusted(seq=self._next_seq, ts=self._tick(), sku=sku,
56
+ delta=delta, reason=reason))
57
+
58
+ # -- reading ---------------------------------------------------------
59
+
60
+ def __len__(self) -> int:
61
+ return len(self._events)
62
+
63
+ def __iter__(self) -> Iterator[Event]:
64
+ return iter(self._events)
65
+
66
+ @property
67
+ def head(self) -> int:
68
+ """Sequence number of the most recent event, or 0 when empty."""
69
+ return self._events[-1].seq if self._events else 0
70
+
71
+ def since(self, seq: int) -> List[Event]:
72
+ """Every event appended strictly after `seq`.
73
+
74
+ A projection resumes by passing the sequence number it last applied, so
75
+ this must be exclusive at the lower bound. Making it inclusive would
76
+ replay one already-applied event on every resume.
77
+ """
78
+ return [e for e in self._events if e.seq >= seq]
79
+
80
+ def between(self, low: int, high: int) -> List[Event]:
81
+ """Events with low < seq <= high."""
82
+ return [e for e in self._events if low < e.seq <= high]
83
+
84
+ def for_sku(self, sku: str) -> List[Event]:
85
+ return [e for e in self._events if e.sku == sku]
86
+
87
+ def skus(self) -> List[str]:
88
+ seen: Dict[str, None] = {}
89
+ for event in self._events:
90
+ seen.setdefault(event.sku, None)
91
+ return list(seen)
92
+
93
+ def replay(self, events: Optional[Iterable[Event]] = None) -> List[Event]:
94
+ """Materialise an event iterable, defaulting to the whole log."""
95
+ return list(self._events if events is None else events)
source/corpus/python/ledger/tasks/audit-findings/task.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 5,
5
+ "instruction": "Three findings from the stock audit. They are unrelated; all three need fixing.\n\n1. Valuation and cost of goods sold are wrong for any SKU received at more than\n one unit cost. The ledger is documented as valuing inventory first-in,\n first-out.\n\n2. A SKU sitting exactly at its configured reorder point produces no\n replenishment suggestion, and we ran out during the supplier lead time. The\n reorder point is meant to be inclusive.\n\n3. Catching a projection up a second time raises rather than applying only what\n is new. A projection is supposed to be resumable, and catching up with\n nothing new appended must apply zero events.",
6
+ "compound": true
7
+ }
source/corpus/python/ledger/tasks/audit-findings/tests/test_catch_up.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, StockProjection
4
+ from ledger.errors import SequenceError
5
+
6
+
7
+ class TestIncrementalCatchUp(unittest.TestCase):
8
+ def test_catch_up_twice_across_new_events(self):
9
+ store = EventStore()
10
+ store.receive("widget", 100, 2.50)
11
+ stock = StockProjection()
12
+ stock.catch_up(store)
13
+ store.ship("widget", 30)
14
+ stock.catch_up(store)
15
+ self.assertEqual(stock.on_hand("widget"), 70)
16
+
17
+ def test_catch_up_with_nothing_new_is_a_noop(self):
18
+ store = EventStore()
19
+ store.receive("widget", 10, 1.0)
20
+ stock = StockProjection()
21
+ self.assertEqual(stock.catch_up(store), 1)
22
+ self.assertEqual(stock.catch_up(store), 0)
23
+ self.assertEqual(stock.on_hand("widget"), 10)
24
+
25
+ def test_many_incremental_catch_ups_match_one_big_one(self):
26
+ incremental = StockProjection()
27
+ store = EventStore()
28
+ for i in range(1, 6):
29
+ store.receive("bolt", i * 10, 1.0)
30
+ incremental.catch_up(store)
31
+ oneshot = StockProjection()
32
+ oneshot.catch_up(store)
33
+ self.assertEqual(incremental.levels, oneshot.levels)
34
+ self.assertEqual(incremental.on_hand("bolt"), 150)
35
+
36
+
37
+ class TestOrderingGuaranteesPreserved(unittest.TestCase):
38
+ """Deleting the ordering check would hide the symptom but corrupt totals."""
39
+
40
+ def test_replaying_an_applied_event_is_still_rejected(self):
41
+ store = EventStore()
42
+ store.receive("widget", 5, 1.0)
43
+ stock = StockProjection()
44
+ stock.catch_up(store)
45
+ already_applied = list(store)[0]
46
+ with self.assertRaises(SequenceError):
47
+ stock.apply(already_applied)
48
+
49
+ def test_store_since_is_exclusive_at_the_lower_bound(self):
50
+ store = EventStore()
51
+ store.receive("a", 1, 1.0)
52
+ store.receive("b", 1, 1.0)
53
+ store.receive("c", 1, 1.0)
54
+ self.assertEqual([e.seq for e in store.since(0)], [1, 2, 3])
55
+ self.assertEqual([e.seq for e in store.since(1)], [2, 3])
56
+ self.assertEqual([e.seq for e in store.since(3)], [])
source/corpus/python/ledger/tasks/audit-findings/tests/test_reorder.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, ReorderPolicy, StockProjection
4
+
5
+
6
+ def stock_at(levels):
7
+ store = EventStore()
8
+ for sku, qty in levels.items():
9
+ if qty > 0:
10
+ store.receive(sku, qty, 1.0)
11
+ projection = StockProjection()
12
+ projection.catch_up(store)
13
+ for sku in levels:
14
+ projection.levels.setdefault(sku, 0)
15
+ return projection
16
+
17
+
18
+ class TestReorderBoundary(unittest.TestCase):
19
+ def test_sku_exactly_at_threshold_is_suggested(self):
20
+ policy = ReorderPolicy({"widget": 10}, {"widget": 40})
21
+ out = policy.suggest(stock_at({"widget": 10}))
22
+ self.assertEqual([s.sku for s in out], ["widget"])
23
+ self.assertEqual(out[0].order_qty, 30)
24
+
25
+ def test_sku_below_threshold_is_still_suggested(self):
26
+ policy = ReorderPolicy({"widget": 10}, {"widget": 40})
27
+ out = policy.suggest(stock_at({"widget": 3}))
28
+ self.assertEqual([s.sku for s in out], ["widget"])
29
+ self.assertEqual(out[0].order_qty, 37)
30
+
31
+ def test_sku_above_threshold_is_not_suggested(self):
32
+ policy = ReorderPolicy({"widget": 10}, {"widget": 40})
33
+ self.assertEqual(policy.suggest(stock_at({"widget": 11})), [])
34
+
35
+ def test_target_already_reached_yields_nothing(self):
36
+ policy = ReorderPolicy({"widget": 40}, {"widget": 40})
37
+ self.assertEqual(policy.suggest(stock_at({"widget": 40})), [])
38
+
39
+ def test_multiple_skus_reported_in_sorted_order(self):
40
+ policy = ReorderPolicy({"b": 5, "a": 5}, {"b": 10, "a": 10})
41
+ out = policy.suggest(stock_at({"a": 5, "b": 5}))
42
+ self.assertEqual([s.sku for s in out], ["a", "b"])
source/corpus/python/ledger/tasks/audit-findings/tests/test_valuation.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, Valuation
4
+
5
+
6
+ def valued(events):
7
+ store = EventStore()
8
+ for kind, sku, *rest in events:
9
+ getattr(store, kind)(sku, *rest)
10
+ valuation = Valuation()
11
+ valuation.catch_up(store)
12
+ return valuation
13
+
14
+
15
+ class TestFifoCostBasis(unittest.TestCase):
16
+ def test_oldest_lot_is_consumed_first(self):
17
+ v = valued([("receive", "w", 10, 1.00),
18
+ ("receive", "w", 10, 3.00),
19
+ ("ship", "w", 10)])
20
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
21
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
22
+
23
+ def test_shipment_spanning_two_lots(self):
24
+ v = valued([("receive", "w", 10, 1.00),
25
+ ("receive", "w", 10, 3.00),
26
+ ("ship", "w", 15)])
27
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10 * 1.00 + 5 * 3.00)
28
+ self.assertAlmostEqual(v.value_of("w"), 5 * 3.00)
29
+
30
+ def test_three_lots_consumed_in_arrival_order(self):
31
+ v = valued([("receive", "w", 5, 1.00),
32
+ ("receive", "w", 5, 2.00),
33
+ ("receive", "w", 5, 4.00),
34
+ ("ship", "w", 12)])
35
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5 * 1.0 + 5 * 2.0 + 2 * 4.0)
36
+ self.assertAlmostEqual(v.value_of("w"), 3 * 4.00)
37
+
38
+ def test_negative_adjustment_also_consumes_oldest_first(self):
39
+ v = valued([("receive", "w", 10, 1.00),
40
+ ("receive", "w", 10, 3.00),
41
+ ("adjust", "w", -10, "stocktake")])
42
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
43
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
44
+
45
+
46
+ class TestValuationInvariants(unittest.TestCase):
47
+ def test_single_lot_is_unaffected(self):
48
+ v = valued([("receive", "w", 10, 2.00), ("ship", "w", 4)])
49
+ self.assertAlmostEqual(v.cost_of_goods_sold, 8.00)
50
+ self.assertAlmostEqual(v.value_of("w"), 12.00)
51
+
52
+ def test_full_depletion_leaves_no_value(self):
53
+ v = valued([("receive", "w", 5, 1.00),
54
+ ("receive", "w", 5, 9.00),
55
+ ("ship", "w", 10)])
56
+ self.assertAlmostEqual(v.value_of("w"), 0.00)
57
+ self.assertAlmostEqual(v.cost_of_goods_sold, 50.00)
58
+
59
+ def test_separate_skus_do_not_interfere(self):
60
+ v = valued([("receive", "a", 5, 1.00),
61
+ ("receive", "b", 5, 7.00),
62
+ ("ship", "a", 5)])
63
+ self.assertAlmostEqual(v.value_of("b"), 35.00)
64
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5.00)
source/corpus/python/ledger/tasks/audit2-01/break/ledger/policies.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]:
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = warehouses
72
+ ordered.sort(key=lambda w: (-w.priority, w.name))
73
+ available = sum(w.on_hand for w in ordered)
74
+ if available < demand:
75
+ raise InsufficientStock("<multiple>", demand, available)
76
+
77
+ plan: List[Tuple[str, int]] = []
78
+ remaining = demand
79
+ for warehouse in ordered:
80
+ if remaining <= 0:
81
+ break
82
+ take = min(warehouse.on_hand, remaining)
83
+ if take > 0:
84
+ plan.append((warehouse.name, take))
85
+ remaining -= take
86
+ return plan
source/corpus/python/ledger/tasks/audit2-01/break/ledger/store.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only event store with snapshot support.
2
+
3
+ The store owns sequence numbering. Nothing else in the package is allowed to
4
+ assign a sequence number, because the ordering guarantee that projections rely
5
+ on is only as good as the single place that hands the numbers out.
6
+ """
7
+ from typing import Dict, Iterable, Iterator, List, Optional
8
+
9
+ from .errors import SequenceError
10
+ from .events import Adjusted, Event, Received, Shipped
11
+
12
+
13
+ class EventStore:
14
+ """Holds every event ever appended, in order."""
15
+
16
+ def __init__(self) -> None:
17
+ self._events: List[Event] = []
18
+ self._next_seq: int = 1
19
+ self._clock: float = 0.0
20
+
21
+ # -- writing ---------------------------------------------------------
22
+
23
+ def _tick(self) -> float:
24
+ self._clock += 1.0
25
+ return self._clock
26
+
27
+ def _append(self, event: Event) -> Event:
28
+ if event.seq != self._next_seq:
29
+ raise SequenceError(
30
+ f"expected seq {self._next_seq}, got {event.seq}")
31
+ self._events.append(event)
32
+ self._next_seq += 1
33
+ return event
34
+
35
+ def receive(self, sku: str, qty: int, unit_cost: float) -> Received:
36
+ """Record stock arriving."""
37
+ if qty <= 0:
38
+ raise ValueError("received quantity must be positive")
39
+ return self._append(
40
+ Received(seq=self._next_seq, ts=self._tick(), sku=sku,
41
+ qty=qty, unit_cost=unit_cost))
42
+
43
+ def ship(self, sku: str, qty: int) -> Shipped:
44
+ """Record stock leaving. Does not itself check availability."""
45
+ if qty <= 0:
46
+ raise ValueError("shipped quantity must be positive")
47
+ return self._append(
48
+ Shipped(seq=self._next_seq, ts=self._tick(), sku=sku, qty=qty))
49
+
50
+ def adjust(self, sku: str, delta: int, reason: str) -> Adjusted:
51
+ """Record a stocktake correction."""
52
+ if delta == 0:
53
+ raise ValueError("adjustment delta must not be zero")
54
+ return self._append(
55
+ Adjusted(seq=self._next_seq, ts=self._tick(), sku=sku,
56
+ delta=delta, reason=reason))
57
+
58
+ # -- reading ---------------------------------------------------------
59
+
60
+ def __len__(self) -> int:
61
+ return len(self._events)
62
+
63
+ def __iter__(self) -> Iterator[Event]:
64
+ return iter(self._events)
65
+
66
+ @property
67
+ def head(self) -> int:
68
+ """Sequence number of the most recent event, or 0 when empty."""
69
+ return self._events[-1].seq if self._events else 0
70
+
71
+ def since(self, seq: int) -> List[Event]:
72
+ """Every event appended strictly after `seq`.
73
+
74
+ A projection resumes by passing the sequence number it last applied, so
75
+ this must be exclusive at the lower bound. Making it inclusive would
76
+ replay one already-applied event on every resume.
77
+ """
78
+ return [e for e in self._events if e.seq > seq]
79
+
80
+ def between(self, low: int, high: int) -> List[Event]:
81
+ """Events with low < seq <= high."""
82
+ return [e for e in self._events if low <= e.seq <= high]
83
+
84
+ def for_sku(self, sku: str) -> List[Event]:
85
+ return [e for e in self._events if e.sku == sku]
86
+
87
+ def skus(self) -> List[str]:
88
+ seen: Dict[str, None] = {}
89
+ for event in self._events:
90
+ seen.setdefault(event.sku, None)
91
+ return list(seen)
92
+
93
+ def replay(self, events: Optional[Iterable[Event]] = None) -> List[Event]:
94
+ """Materialise an event iterable, defaulting to the whole log."""
95
+ return list(self._events if events is None else events)
source/corpus/python/ledger/tasks/audit2-01/task.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 5,
5
+ "compound": true,
6
+ "ingredients": [
7
+ "allocate-mutates",
8
+ "between-boundary"
9
+ ],
10
+ "instruction": "2 findings from this week's triage. They have separate causes and are not related to one another; all 2 need fixing.\n\n1. A caller that allocates twice from the same warehouse list gets a different plan the second time, and reports that their own list comes back reordered afterwards.\n allocate() is supposed to be free of side effects on its arguments. Fix it.\n\n2. Our per-period stock report double-counts events on period boundaries.\n Consecutive reports are produced by asking the store for the events between the\n previous report's last sequence number and the current one. An event landing\n exactly on a boundary shows up in both the earlier report and the later one.\n The range is documented as excluding its lower bound and including its upper."
11
+ }
source/corpus/python/ledger/tasks/audit2-01/tests/test_allocate.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import allocate
4
+ from ledger.policies import Warehouse
5
+
6
+
7
+ def houses():
8
+ return [Warehouse("north", 1, 5),
9
+ Warehouse("south", 3, 5),
10
+ Warehouse("east", 2, 5)]
11
+
12
+
13
+ class TestAllocateIsPure(unittest.TestCase):
14
+ def test_caller_list_order_is_untouched(self):
15
+ warehouses = houses()
16
+ before = [w.name for w in warehouses]
17
+ allocate(6, warehouses)
18
+ self.assertEqual([w.name for w in warehouses], before)
19
+
20
+ def test_repeated_calls_agree(self):
21
+ warehouses = houses()
22
+ first = allocate(7, warehouses)
23
+ second = allocate(7, warehouses)
24
+ self.assertEqual(first, second)
25
+
26
+
27
+ class TestAllocateBehaviour(unittest.TestCase):
28
+ def test_highest_priority_first(self):
29
+ self.assertEqual(allocate(5, houses()), [("south", 5)])
30
+
31
+ def test_spills_into_next_priority(self):
32
+ self.assertEqual(allocate(8, houses()), [("south", 5), ("east", 3)])
33
+
34
+ def test_ties_broken_by_name(self):
35
+ tied = [Warehouse("b", 5, 2), Warehouse("a", 5, 2)]
36
+ self.assertEqual(allocate(3, tied), [("a", 2), ("b", 1)])
37
+
38
+ def test_insufficient_stock_raises(self):
39
+ from ledger.errors import InsufficientStock
40
+ with self.assertRaises(InsufficientStock):
41
+ allocate(999, houses())
source/corpus/python/ledger/tasks/audit2-01/tests/test_between.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import unittest
3
+
4
+ from ledger import EventStore
5
+
6
+
7
+ def store_with(n):
8
+ store = EventStore()
9
+ for i in range(n):
10
+ store.receive(f"sku{i}", 1, 1.0)
11
+ return store
12
+
13
+
14
+ class TestBetweenIsHalfOpen(unittest.TestCase):
15
+ def test_lower_bound_is_excluded(self):
16
+ self.assertEqual([e.seq for e in store_with(5).between(2, 4)], [3, 4])
17
+
18
+ def test_consecutive_ranges_do_not_overlap(self):
19
+ store = store_with(6)
20
+ first = {e.seq for e in store.between(0, 3)}
21
+ second = {e.seq for e in store.between(3, 6)}
22
+ self.assertEqual(first & second, set())
23
+
24
+ def test_consecutive_ranges_leave_no_gap(self):
25
+ store = store_with(6)
26
+ seen = {e.seq for e in store.between(0, 3)} | {e.seq for e in store.between(3, 6)}
27
+ self.assertEqual(seen, {1, 2, 3, 4, 5, 6})
28
+
29
+ def test_empty_range(self):
30
+ self.assertEqual(store_with(5).between(3, 3), [])
31
+
32
+
33
+ class TestBetweenOtherwiseWorks(unittest.TestCase):
34
+ def test_upper_bound_is_included(self):
35
+ self.assertIn(4, [e.seq for e in store_with(5).between(2, 4)])
36
+
37
+ def test_full_range(self):
38
+ self.assertEqual(len(store_with(5).between(0, 5)), 5)
39
+
40
+ def test_beyond_the_end(self):
41
+ self.assertEqual(len(store_with(3).between(0, 99)), 3)
source/corpus/python/ledger/tasks/audit2-02/break/ledger/policies.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]:
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = warehouses
72
+ ordered.sort(key=lambda w: (-w.priority, w.name))
73
+ available = sum(w.on_hand for w in ordered)
74
+ if available < demand:
75
+ raise InsufficientStock("<multiple>", demand, available)
76
+
77
+ plan: List[Tuple[str, int]] = []
78
+ remaining = demand
79
+ for warehouse in ordered:
80
+ if remaining <= 0:
81
+ break
82
+ take = min(warehouse.on_hand, remaining)
83
+ if take > 0:
84
+ plan.append((warehouse.name, take))
85
+ remaining -= take
86
+ return plan
source/corpus/python/ledger/tasks/audit2-02/break/ledger/projections.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read models built by folding the event log.
2
+
3
+ A projection is resumable: it remembers the last sequence number it applied
4
+ and asks the store only for what came after. That is what keeps a long ledger
5
+ cheap to query, and it is why the store's `since` boundary matters so much.
6
+ """
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, List, Optional, Tuple
9
+
10
+ from .errors import SequenceError, UnknownSku
11
+ from .events import Adjusted, Event, Received, Shipped
12
+ from .store import EventStore
13
+
14
+
15
+ class StockProjection:
16
+ """Units on hand per SKU."""
17
+
18
+ def __init__(self) -> None:
19
+ self.levels: Dict[str, int] = {}
20
+ self.last_seq: int = 0
21
+
22
+ def apply(self, event: Event) -> None:
23
+ """Fold a single event into the running totals."""
24
+ if event.seq <= self.last_seq:
25
+ raise SequenceError(
26
+ f"event {event.seq} already applied (at {self.last_seq})")
27
+ current = self.levels.get(event.sku, 0)
28
+ if isinstance(event, Received):
29
+ current += event.qty
30
+ elif isinstance(event, Shipped):
31
+ current -= event.qty
32
+ elif isinstance(event, Adjusted):
33
+ current += event.delta
34
+ self.levels[event.sku] = current
35
+ self.last_seq = event.seq
36
+
37
+ def catch_up(self, store: EventStore) -> int:
38
+ """Apply everything appended since the last call. Returns the count."""
39
+ pending = store.since(self.last_seq)
40
+ for event in pending:
41
+ self.apply(event)
42
+ return len(pending)
43
+
44
+ def on_hand(self, sku: str) -> int:
45
+ if sku not in self.levels:
46
+ raise UnknownSku(sku)
47
+ return self.levels[sku]
48
+
49
+ def negative_skus(self) -> List[str]:
50
+ """SKUs the log says we hold a negative quantity of."""
51
+ return sorted(s for s, n in self.levels.items() if n < 0)
52
+
53
+
54
+ @dataclass
55
+ class Lot:
56
+ """One receipt still carrying unconsumed units."""
57
+ seq: int
58
+ qty: int
59
+ unit_cost: float
60
+
61
+
62
+ class Valuation:
63
+ """Inventory value under first-in, first-out cost basis."""
64
+
65
+ def __init__(self) -> None:
66
+ self.lots: Dict[str, List[Lot]] = {}
67
+ self.last_seq: int = 0
68
+ self.cost_of_goods_sold: float = 0.0
69
+
70
+ def apply(self, event: Event) -> None:
71
+ lots = self.lots.setdefault(event.sku, [])
72
+ if isinstance(event, Received):
73
+ lots.append(Lot(seq=event.seq, qty=event.qty,
74
+ unit_cost=event.unit_cost))
75
+ elif isinstance(event, Shipped):
76
+ self._consume(lots, event.qty)
77
+ elif isinstance(event, Adjusted):
78
+ if event.delta > 0:
79
+ unit_cost = lots[-1].unit_cost if lots else 0.0
80
+ lots.append(Lot(seq=event.seq, qty=event.delta,
81
+ unit_cost=unit_cost))
82
+ else:
83
+ self._consume(lots, -event.delta)
84
+ self.last_seq = event.seq
85
+
86
+ def _consume(self, lots: List[Lot], qty: int) -> None:
87
+ """Draw `qty` units from the oldest lots first."""
88
+ remaining = qty
89
+ while remaining > 0 and lots:
90
+ oldest = lots[-1]
91
+ take = min(oldest.qty, remaining)
92
+ self.cost_of_goods_sold += take * oldest.unit_cost
93
+ oldest.qty -= take
94
+ remaining -= take
95
+ if oldest.qty == 0:
96
+ lots.pop()
97
+
98
+ def catch_up(self, store: EventStore) -> int:
99
+ pending = store.since(self.last_seq)
100
+ for event in pending:
101
+ self.apply(event)
102
+ return len(pending)
103
+
104
+ def value_of(self, sku: str) -> float:
105
+ """Total carrying value of the units still on hand for one SKU."""
106
+ if sku not in self.lots:
107
+ raise UnknownSku(sku)
108
+ return sum(lot.qty * lot.unit_cost for lot in self.lots[sku])
109
+
110
+ def total_value(self) -> float:
111
+ return sum(lot.qty * lot.unit_cost
112
+ for lots in self.lots.values() for lot in lots)
source/corpus/python/ledger/tasks/audit2-02/task.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 5,
5
+ "compound": true,
6
+ "ingredients": [
7
+ "allocate-mutates",
8
+ "fifo-lifo"
9
+ ],
10
+ "instruction": "2 findings from this week's triage. They have separate causes and are not related to one another; all 2 need fixing.\n\n1. A caller that allocates twice from the same warehouse list gets a different plan the second time, and reports that their own list comes back reordered afterwards.\n allocate() is supposed to be free of side effects on its arguments. Fix it.\n\n2. Our finance team reports that inventory valuation and cost of goods sold are wrong whenever a SKU has been received at more than one unit cost.\n Concrete case: receive 10 units at 1.00, then 10 units at 3.00, then ship 10 units. Cost of goods sold should be 10.00 and the remaining inventory should be valued at 30.00. We are getting those two numbers the other way round.\n The ledger is documented as valuing inventory on a first-in, first-out basis. Make it do that."
11
+ }
source/corpus/python/ledger/tasks/audit2-02/tests/test_allocate.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import allocate
4
+ from ledger.policies import Warehouse
5
+
6
+
7
+ def houses():
8
+ return [Warehouse("north", 1, 5),
9
+ Warehouse("south", 3, 5),
10
+ Warehouse("east", 2, 5)]
11
+
12
+
13
+ class TestAllocateIsPure(unittest.TestCase):
14
+ def test_caller_list_order_is_untouched(self):
15
+ warehouses = houses()
16
+ before = [w.name for w in warehouses]
17
+ allocate(6, warehouses)
18
+ self.assertEqual([w.name for w in warehouses], before)
19
+
20
+ def test_repeated_calls_agree(self):
21
+ warehouses = houses()
22
+ first = allocate(7, warehouses)
23
+ second = allocate(7, warehouses)
24
+ self.assertEqual(first, second)
25
+
26
+
27
+ class TestAllocateBehaviour(unittest.TestCase):
28
+ def test_highest_priority_first(self):
29
+ self.assertEqual(allocate(5, houses()), [("south", 5)])
30
+
31
+ def test_spills_into_next_priority(self):
32
+ self.assertEqual(allocate(8, houses()), [("south", 5), ("east", 3)])
33
+
34
+ def test_ties_broken_by_name(self):
35
+ tied = [Warehouse("b", 5, 2), Warehouse("a", 5, 2)]
36
+ self.assertEqual(allocate(3, tied), [("a", 2), ("b", 1)])
37
+
38
+ def test_insufficient_stock_raises(self):
39
+ from ledger.errors import InsufficientStock
40
+ with self.assertRaises(InsufficientStock):
41
+ allocate(999, houses())
source/corpus/python/ledger/tasks/audit2-02/tests/test_valuation.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, Valuation
4
+
5
+
6
+ def valued(events):
7
+ store = EventStore()
8
+ for kind, sku, *rest in events:
9
+ getattr(store, kind)(sku, *rest)
10
+ valuation = Valuation()
11
+ valuation.catch_up(store)
12
+ return valuation
13
+
14
+
15
+ class TestFifoCostBasis(unittest.TestCase):
16
+ def test_oldest_lot_is_consumed_first(self):
17
+ v = valued([("receive", "w", 10, 1.00),
18
+ ("receive", "w", 10, 3.00),
19
+ ("ship", "w", 10)])
20
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
21
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
22
+
23
+ def test_shipment_spanning_two_lots(self):
24
+ v = valued([("receive", "w", 10, 1.00),
25
+ ("receive", "w", 10, 3.00),
26
+ ("ship", "w", 15)])
27
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10 * 1.00 + 5 * 3.00)
28
+ self.assertAlmostEqual(v.value_of("w"), 5 * 3.00)
29
+
30
+ def test_three_lots_consumed_in_arrival_order(self):
31
+ v = valued([("receive", "w", 5, 1.00),
32
+ ("receive", "w", 5, 2.00),
33
+ ("receive", "w", 5, 4.00),
34
+ ("ship", "w", 12)])
35
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5 * 1.0 + 5 * 2.0 + 2 * 4.0)
36
+ self.assertAlmostEqual(v.value_of("w"), 3 * 4.00)
37
+
38
+ def test_negative_adjustment_also_consumes_oldest_first(self):
39
+ v = valued([("receive", "w", 10, 1.00),
40
+ ("receive", "w", 10, 3.00),
41
+ ("adjust", "w", -10, "stocktake")])
42
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
43
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
44
+
45
+
46
+ class TestValuationInvariants(unittest.TestCase):
47
+ def test_single_lot_is_unaffected(self):
48
+ v = valued([("receive", "w", 10, 2.00), ("ship", "w", 4)])
49
+ self.assertAlmostEqual(v.cost_of_goods_sold, 8.00)
50
+ self.assertAlmostEqual(v.value_of("w"), 12.00)
51
+
52
+ def test_full_depletion_leaves_no_value(self):
53
+ v = valued([("receive", "w", 5, 1.00),
54
+ ("receive", "w", 5, 9.00),
55
+ ("ship", "w", 10)])
56
+ self.assertAlmostEqual(v.value_of("w"), 0.00)
57
+ self.assertAlmostEqual(v.cost_of_goods_sold, 50.00)
58
+
59
+ def test_separate_skus_do_not_interfere(self):
60
+ v = valued([("receive", "a", 5, 1.00),
61
+ ("receive", "b", 5, 7.00),
62
+ ("ship", "a", 5)])
63
+ self.assertAlmostEqual(v.value_of("b"), 35.00)
64
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5.00)
source/corpus/python/ledger/tasks/audit2-03/break/ledger/policies.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]:
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = warehouses
72
+ ordered.sort(key=lambda w: (-w.priority, w.name))
73
+ available = sum(w.on_hand for w in ordered)
74
+ if available < demand:
75
+ raise InsufficientStock("<multiple>", demand, available)
76
+
77
+ plan: List[Tuple[str, int]] = []
78
+ remaining = demand
79
+ for warehouse in ordered:
80
+ if remaining <= 0:
81
+ break
82
+ take = min(warehouse.on_hand, remaining)
83
+ if take > 0:
84
+ plan.append((warehouse.name, take))
85
+ remaining -= take
86
+ return plan
source/corpus/python/ledger/tasks/audit2-03/break/ledger/projections.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read models built by folding the event log.
2
+
3
+ A projection is resumable: it remembers the last sequence number it applied
4
+ and asks the store only for what came after. That is what keeps a long ledger
5
+ cheap to query, and it is why the store's `since` boundary matters so much.
6
+ """
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, List, Optional, Tuple
9
+
10
+ from .errors import SequenceError, UnknownSku
11
+ from .events import Adjusted, Event, Received, Shipped
12
+ from .store import EventStore
13
+
14
+
15
+ class StockProjection:
16
+ """Units on hand per SKU."""
17
+
18
+ def __init__(self) -> None:
19
+ self.levels: Dict[str, int] = {}
20
+ self.last_seq: int = 0
21
+
22
+ def apply(self, event: Event) -> None:
23
+ """Fold a single event into the running totals."""
24
+ if event.seq <= self.last_seq:
25
+ raise SequenceError(
26
+ f"event {event.seq} already applied (at {self.last_seq})")
27
+ current = self.levels.get(event.sku, 0)
28
+ if isinstance(event, Received):
29
+ current += event.qty
30
+ elif isinstance(event, Shipped):
31
+ current -= event.qty
32
+ elif isinstance(event, Adjusted):
33
+ current += event.delta
34
+ self.levels[event.sku] = current
35
+ self.last_seq = event.seq
36
+
37
+ def catch_up(self, store: EventStore) -> int:
38
+ """Apply everything appended since the last call. Returns the count."""
39
+ pending = store.since(self.last_seq)
40
+ for event in pending:
41
+ self.apply(event)
42
+ return len(pending)
43
+
44
+ def on_hand(self, sku: str) -> int:
45
+ if sku not in self.levels:
46
+ raise UnknownSku(sku)
47
+ return self.levels[sku]
48
+
49
+ def negative_skus(self) -> List[str]:
50
+ """SKUs the log says we hold a negative quantity of."""
51
+ return sorted(s for s, n in self.levels.items() if n < 0)
52
+
53
+
54
+ @dataclass
55
+ class Lot:
56
+ """One receipt still carrying unconsumed units."""
57
+ seq: int
58
+ qty: int
59
+ unit_cost: float
60
+
61
+
62
+ class Valuation:
63
+ """Inventory value under first-in, first-out cost basis."""
64
+
65
+ def __init__(self) -> None:
66
+ self.lots: Dict[str, List[Lot]] = {}
67
+ self.last_seq: int = 0
68
+ self.cost_of_goods_sold: float = 0.0
69
+
70
+ def apply(self, event: Event) -> None:
71
+ lots = self.lots.setdefault(event.sku, [])
72
+ if isinstance(event, Received):
73
+ lots.append(Lot(seq=event.seq, qty=event.qty,
74
+ unit_cost=event.unit_cost))
75
+ elif isinstance(event, Shipped):
76
+ self._consume(lots, event.qty)
77
+ elif isinstance(event, Adjusted):
78
+ if event.delta > 0:
79
+ unit_cost = lots[-1].unit_cost if lots else 0.0
80
+ lots.append(Lot(seq=event.seq, qty=event.delta,
81
+ unit_cost=unit_cost))
82
+ else:
83
+ self._consume(lots, -event.delta)
84
+ self.last_seq = event.seq
85
+
86
+ def _consume(self, lots: List[Lot], qty: int) -> None:
87
+ """Draw `qty` units from the oldest lots first."""
88
+ remaining = qty
89
+ while remaining > 0 and lots:
90
+ oldest = lots[-1]
91
+ take = min(oldest.qty, remaining)
92
+ self.cost_of_goods_sold += take * oldest.unit_cost
93
+ oldest.qty -= take
94
+ remaining -= take
95
+ if oldest.qty == 0:
96
+ lots.pop()
97
+
98
+ def catch_up(self, store: EventStore) -> int:
99
+ pending = store.since(self.last_seq)
100
+ for event in pending:
101
+ self.apply(event)
102
+ return len(pending)
103
+
104
+ def value_of(self, sku: str) -> float:
105
+ """Total carrying value of the units still on hand for one SKU."""
106
+ if sku not in self.lots:
107
+ raise UnknownSku(sku)
108
+ return sum(lot.qty * lot.unit_cost for lot in self.lots[sku])
109
+
110
+ def total_value(self) -> float:
111
+ return sum(lot.qty * lot.unit_cost
112
+ for lots in self.lots.values() for lot in lots)
source/corpus/python/ledger/tasks/audit2-03/break/ledger/store.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only event store with snapshot support.
2
+
3
+ The store owns sequence numbering. Nothing else in the package is allowed to
4
+ assign a sequence number, because the ordering guarantee that projections rely
5
+ on is only as good as the single place that hands the numbers out.
6
+ """
7
+ from typing import Dict, Iterable, Iterator, List, Optional
8
+
9
+ from .errors import SequenceError
10
+ from .events import Adjusted, Event, Received, Shipped
11
+
12
+
13
+ class EventStore:
14
+ """Holds every event ever appended, in order."""
15
+
16
+ def __init__(self) -> None:
17
+ self._events: List[Event] = []
18
+ self._next_seq: int = 1
19
+ self._clock: float = 0.0
20
+
21
+ # -- writing ---------------------------------------------------------
22
+
23
+ def _tick(self) -> float:
24
+ self._clock += 1.0
25
+ return self._clock
26
+
27
+ def _append(self, event: Event) -> Event:
28
+ if event.seq != self._next_seq:
29
+ raise SequenceError(
30
+ f"expected seq {self._next_seq}, got {event.seq}")
31
+ self._events.append(event)
32
+ self._next_seq += 1
33
+ return event
34
+
35
+ def receive(self, sku: str, qty: int, unit_cost: float) -> Received:
36
+ """Record stock arriving."""
37
+ if qty <= 0:
38
+ raise ValueError("received quantity must be positive")
39
+ return self._append(
40
+ Received(seq=self._next_seq, ts=self._tick(), sku=sku,
41
+ qty=qty, unit_cost=unit_cost))
42
+
43
+ def ship(self, sku: str, qty: int) -> Shipped:
44
+ """Record stock leaving. Does not itself check availability."""
45
+ if qty <= 0:
46
+ raise ValueError("shipped quantity must be positive")
47
+ return self._append(
48
+ Shipped(seq=self._next_seq, ts=self._tick(), sku=sku, qty=qty))
49
+
50
+ def adjust(self, sku: str, delta: int, reason: str) -> Adjusted:
51
+ """Record a stocktake correction."""
52
+ if delta == 0:
53
+ raise ValueError("adjustment delta must not be zero")
54
+ return self._append(
55
+ Adjusted(seq=self._next_seq, ts=self._tick(), sku=sku,
56
+ delta=delta, reason=reason))
57
+
58
+ # -- reading ---------------------------------------------------------
59
+
60
+ def __len__(self) -> int:
61
+ return len(self._events)
62
+
63
+ def __iter__(self) -> Iterator[Event]:
64
+ return iter(self._events)
65
+
66
+ @property
67
+ def head(self) -> int:
68
+ """Sequence number of the most recent event, or 0 when empty."""
69
+ return self._events[-1].seq if self._events else 0
70
+
71
+ def since(self, seq: int) -> List[Event]:
72
+ """Every event appended strictly after `seq`.
73
+
74
+ A projection resumes by passing the sequence number it last applied, so
75
+ this must be exclusive at the lower bound. Making it inclusive would
76
+ replay one already-applied event on every resume.
77
+ """
78
+ return [e for e in self._events if e.seq >= seq]
79
+
80
+ def between(self, low: int, high: int) -> List[Event]:
81
+ """Events with low < seq <= high."""
82
+ return [e for e in self._events if low < e.seq <= high]
83
+
84
+ def for_sku(self, sku: str) -> List[Event]:
85
+ return [e for e in self._events if e.sku == sku]
86
+
87
+ def skus(self) -> List[str]:
88
+ seen: Dict[str, None] = {}
89
+ for event in self._events:
90
+ seen.setdefault(event.sku, None)
91
+ return list(seen)
92
+
93
+ def replay(self, events: Optional[Iterable[Event]] = None) -> List[Event]:
94
+ """Materialise an event iterable, defaulting to the whole log."""
95
+ return list(self._events if events is None else events)
source/corpus/python/ledger/tasks/audit2-03/task.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 5,
5
+ "compound": true,
6
+ "ingredients": [
7
+ "allocate-mutates",
8
+ "since-inclusive"
9
+ ],
10
+ "instruction": "2 findings from this week's triage. They have separate causes and are not related to one another; all 2 need fixing.\n\n1. A caller that allocates twice from the same warehouse list gets a different plan the second time, and reports that their own list comes back reordered afterwards.\n allocate() is supposed to be free of side effects on its arguments. Fix it.\n\n2. Catching a projection up more than once crashes.\n Reproduction: build an EventStore, receive some stock, call StockProjection.catch_up(store), append another event, then call catch_up(store) again. The second call raises SequenceError complaining that an event has already been applied.\n A projection is supposed to be resumable -- repeatedly catching up must be safe, and calling it when nothing new has been appended must be a no-op that applies zero events. Find the underlying cause and fix it. Do not weaken the ledger's ordering guarantees to make the symptom disappear."
11
+ }
source/corpus/python/ledger/tasks/audit2-03/tests/test_allocate.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import allocate
4
+ from ledger.policies import Warehouse
5
+
6
+
7
+ def houses():
8
+ return [Warehouse("north", 1, 5),
9
+ Warehouse("south", 3, 5),
10
+ Warehouse("east", 2, 5)]
11
+
12
+
13
+ class TestAllocateIsPure(unittest.TestCase):
14
+ def test_caller_list_order_is_untouched(self):
15
+ warehouses = houses()
16
+ before = [w.name for w in warehouses]
17
+ allocate(6, warehouses)
18
+ self.assertEqual([w.name for w in warehouses], before)
19
+
20
+ def test_repeated_calls_agree(self):
21
+ warehouses = houses()
22
+ first = allocate(7, warehouses)
23
+ second = allocate(7, warehouses)
24
+ self.assertEqual(first, second)
25
+
26
+
27
+ class TestAllocateBehaviour(unittest.TestCase):
28
+ def test_highest_priority_first(self):
29
+ self.assertEqual(allocate(5, houses()), [("south", 5)])
30
+
31
+ def test_spills_into_next_priority(self):
32
+ self.assertEqual(allocate(8, houses()), [("south", 5), ("east", 3)])
33
+
34
+ def test_ties_broken_by_name(self):
35
+ tied = [Warehouse("b", 5, 2), Warehouse("a", 5, 2)]
36
+ self.assertEqual(allocate(3, tied), [("a", 2), ("b", 1)])
37
+
38
+ def test_insufficient_stock_raises(self):
39
+ from ledger.errors import InsufficientStock
40
+ with self.assertRaises(InsufficientStock):
41
+ allocate(999, houses())
source/corpus/python/ledger/tasks/audit2-03/tests/test_between.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import unittest
3
+
4
+ from ledger import EventStore
5
+
6
+
7
+ def store_with(n):
8
+ store = EventStore()
9
+ for i in range(n):
10
+ store.receive(f"sku{i}", 1, 1.0)
11
+ return store
12
+
13
+
14
+ class TestBetweenIsHalfOpen(unittest.TestCase):
15
+ def test_lower_bound_is_excluded(self):
16
+ self.assertEqual([e.seq for e in store_with(5).between(2, 4)], [3, 4])
17
+
18
+ def test_consecutive_ranges_do_not_overlap(self):
19
+ store = store_with(6)
20
+ first = {e.seq for e in store.between(0, 3)}
21
+ second = {e.seq for e in store.between(3, 6)}
22
+ self.assertEqual(first & second, set())
23
+
24
+ def test_consecutive_ranges_leave_no_gap(self):
25
+ store = store_with(6)
26
+ seen = {e.seq for e in store.between(0, 3)} | {e.seq for e in store.between(3, 6)}
27
+ self.assertEqual(seen, {1, 2, 3, 4, 5, 6})
28
+
29
+ def test_empty_range(self):
30
+ self.assertEqual(store_with(5).between(3, 3), [])
31
+
32
+
33
+ class TestBetweenOtherwiseWorks(unittest.TestCase):
34
+ def test_upper_bound_is_included(self):
35
+ self.assertIn(4, [e.seq for e in store_with(5).between(2, 4)])
36
+
37
+ def test_full_range(self):
38
+ self.assertEqual(len(store_with(5).between(0, 5)), 5)
39
+
40
+ def test_beyond_the_end(self):
41
+ self.assertEqual(len(store_with(3).between(0, 99)), 3)
source/corpus/python/ledger/tasks/audit2-03/tests/test_catch_up.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, StockProjection
4
+ from ledger.errors import SequenceError
5
+
6
+
7
+ class TestIncrementalCatchUp(unittest.TestCase):
8
+ def test_catch_up_twice_across_new_events(self):
9
+ store = EventStore()
10
+ store.receive("widget", 100, 2.50)
11
+ stock = StockProjection()
12
+ stock.catch_up(store)
13
+ store.ship("widget", 30)
14
+ stock.catch_up(store)
15
+ self.assertEqual(stock.on_hand("widget"), 70)
16
+
17
+ def test_catch_up_with_nothing_new_is_a_noop(self):
18
+ store = EventStore()
19
+ store.receive("widget", 10, 1.0)
20
+ stock = StockProjection()
21
+ self.assertEqual(stock.catch_up(store), 1)
22
+ self.assertEqual(stock.catch_up(store), 0)
23
+ self.assertEqual(stock.on_hand("widget"), 10)
24
+
25
+ def test_many_incremental_catch_ups_match_one_big_one(self):
26
+ incremental = StockProjection()
27
+ store = EventStore()
28
+ for i in range(1, 6):
29
+ store.receive("bolt", i * 10, 1.0)
30
+ incremental.catch_up(store)
31
+ oneshot = StockProjection()
32
+ oneshot.catch_up(store)
33
+ self.assertEqual(incremental.levels, oneshot.levels)
34
+ self.assertEqual(incremental.on_hand("bolt"), 150)
35
+
36
+
37
+ class TestOrderingGuaranteesPreserved(unittest.TestCase):
38
+ """Deleting the ordering check would hide the symptom but corrupt totals."""
39
+
40
+ def test_replaying_an_applied_event_is_still_rejected(self):
41
+ store = EventStore()
42
+ store.receive("widget", 5, 1.0)
43
+ stock = StockProjection()
44
+ stock.catch_up(store)
45
+ already_applied = list(store)[0]
46
+ with self.assertRaises(SequenceError):
47
+ stock.apply(already_applied)
48
+
49
+ def test_store_since_is_exclusive_at_the_lower_bound(self):
50
+ store = EventStore()
51
+ store.receive("a", 1, 1.0)
52
+ store.receive("b", 1, 1.0)
53
+ store.receive("c", 1, 1.0)
54
+ self.assertEqual([e.seq for e in store.since(0)], [1, 2, 3])
55
+ self.assertEqual([e.seq for e in store.since(1)], [2, 3])
56
+ self.assertEqual([e.seq for e in store.since(3)], [])
source/corpus/python/ledger/tasks/audit2-03/tests/test_valuation.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, Valuation
4
+
5
+
6
+ def valued(events):
7
+ store = EventStore()
8
+ for kind, sku, *rest in events:
9
+ getattr(store, kind)(sku, *rest)
10
+ valuation = Valuation()
11
+ valuation.catch_up(store)
12
+ return valuation
13
+
14
+
15
+ class TestFifoCostBasis(unittest.TestCase):
16
+ def test_oldest_lot_is_consumed_first(self):
17
+ v = valued([("receive", "w", 10, 1.00),
18
+ ("receive", "w", 10, 3.00),
19
+ ("ship", "w", 10)])
20
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
21
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
22
+
23
+ def test_shipment_spanning_two_lots(self):
24
+ v = valued([("receive", "w", 10, 1.00),
25
+ ("receive", "w", 10, 3.00),
26
+ ("ship", "w", 15)])
27
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10 * 1.00 + 5 * 3.00)
28
+ self.assertAlmostEqual(v.value_of("w"), 5 * 3.00)
29
+
30
+ def test_three_lots_consumed_in_arrival_order(self):
31
+ v = valued([("receive", "w", 5, 1.00),
32
+ ("receive", "w", 5, 2.00),
33
+ ("receive", "w", 5, 4.00),
34
+ ("ship", "w", 12)])
35
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5 * 1.0 + 5 * 2.0 + 2 * 4.0)
36
+ self.assertAlmostEqual(v.value_of("w"), 3 * 4.00)
37
+
38
+ def test_negative_adjustment_also_consumes_oldest_first(self):
39
+ v = valued([("receive", "w", 10, 1.00),
40
+ ("receive", "w", 10, 3.00),
41
+ ("adjust", "w", -10, "stocktake")])
42
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
43
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
44
+
45
+
46
+ class TestValuationInvariants(unittest.TestCase):
47
+ def test_single_lot_is_unaffected(self):
48
+ v = valued([("receive", "w", 10, 2.00), ("ship", "w", 4)])
49
+ self.assertAlmostEqual(v.cost_of_goods_sold, 8.00)
50
+ self.assertAlmostEqual(v.value_of("w"), 12.00)
51
+
52
+ def test_full_depletion_leaves_no_value(self):
53
+ v = valued([("receive", "w", 5, 1.00),
54
+ ("receive", "w", 5, 9.00),
55
+ ("ship", "w", 10)])
56
+ self.assertAlmostEqual(v.value_of("w"), 0.00)
57
+ self.assertAlmostEqual(v.cost_of_goods_sold, 50.00)
58
+
59
+ def test_separate_skus_do_not_interfere(self):
60
+ v = valued([("receive", "a", 5, 1.00),
61
+ ("receive", "b", 5, 7.00),
62
+ ("ship", "a", 5)])
63
+ self.assertAlmostEqual(v.value_of("b"), 35.00)
64
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5.00)
source/corpus/python/ledger/tasks/audit2-04/break/ledger/policies.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = sorted(warehouses, key=lambda w: (-w.priority, w.name))
72
+ available = sum(w.on_hand for w in ordered)
73
+ if available < demand:
74
+ raise InsufficientStock("<multiple>", demand, available)
75
+
76
+ plan: List[Tuple[str, int]] = []
77
+ remaining = demand
78
+ for warehouse in ordered:
79
+ if remaining <= 0:
80
+ break
81
+ take = min(warehouse.on_hand, remaining)
82
+ if take > 0:
83
+ plan.append((warehouse.name, take))
84
+ remaining -= take
85
+ return plan
source/corpus/python/ledger/tasks/audit2-04/break/ledger/projections.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read models built by folding the event log.
2
+
3
+ A projection is resumable: it remembers the last sequence number it applied
4
+ and asks the store only for what came after. That is what keeps a long ledger
5
+ cheap to query, and it is why the store's `since` boundary matters so much.
6
+ """
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, List, Optional, Tuple
9
+
10
+ from .errors import SequenceError, UnknownSku
11
+ from .events import Adjusted, Event, Received, Shipped
12
+ from .store import EventStore
13
+
14
+
15
+ class StockProjection:
16
+ """Units on hand per SKU."""
17
+
18
+ def __init__(self) -> None:
19
+ self.levels: Dict[str, int] = {}
20
+ self.last_seq: int = 0
21
+
22
+ def apply(self, event: Event) -> None:
23
+ """Fold a single event into the running totals."""
24
+ if event.seq <= self.last_seq:
25
+ raise SequenceError(
26
+ f"event {event.seq} already applied (at {self.last_seq})")
27
+ current = self.levels.get(event.sku, 0)
28
+ if isinstance(event, Received):
29
+ current += event.qty
30
+ elif isinstance(event, Shipped):
31
+ current -= event.qty
32
+ elif isinstance(event, Adjusted):
33
+ current += event.delta
34
+ self.levels[event.sku] = current
35
+ self.last_seq = event.seq
36
+
37
+ def catch_up(self, store: EventStore) -> int:
38
+ """Apply everything appended since the last call. Returns the count."""
39
+ pending = store.since(self.last_seq)
40
+ for event in pending:
41
+ self.apply(event)
42
+ return len(pending)
43
+
44
+ def on_hand(self, sku: str) -> int:
45
+ if sku not in self.levels:
46
+ raise UnknownSku(sku)
47
+ return self.levels[sku]
48
+
49
+ def negative_skus(self) -> List[str]:
50
+ """SKUs the log says we hold a negative quantity of."""
51
+ return sorted(s for s, n in self.levels.items() if n < 0)
52
+
53
+
54
+ @dataclass
55
+ class Lot:
56
+ """One receipt still carrying unconsumed units."""
57
+ seq: int
58
+ qty: int
59
+ unit_cost: float
60
+
61
+
62
+ class Valuation:
63
+ """Inventory value under first-in, first-out cost basis."""
64
+
65
+ def __init__(self) -> None:
66
+ self.lots: Dict[str, List[Lot]] = {}
67
+ self.last_seq: int = 0
68
+ self.cost_of_goods_sold: float = 0.0
69
+
70
+ def apply(self, event: Event) -> None:
71
+ lots = self.lots.setdefault(event.sku, [])
72
+ if isinstance(event, Received):
73
+ lots.append(Lot(seq=event.seq, qty=event.qty,
74
+ unit_cost=event.unit_cost))
75
+ elif isinstance(event, Shipped):
76
+ self._consume(lots, event.qty)
77
+ elif isinstance(event, Adjusted):
78
+ if event.delta > 0:
79
+ unit_cost = lots[-1].unit_cost if lots else 0.0
80
+ lots.append(Lot(seq=event.seq, qty=event.delta,
81
+ unit_cost=unit_cost))
82
+ else:
83
+ self._consume(lots, -event.delta)
84
+ self.last_seq = event.seq
85
+
86
+ def _consume(self, lots: List[Lot], qty: int) -> None:
87
+ """Draw `qty` units from the oldest lots first."""
88
+ remaining = qty
89
+ while remaining > 0 and lots:
90
+ oldest = lots[-1]
91
+ take = min(oldest.qty, remaining)
92
+ self.cost_of_goods_sold += take * oldest.unit_cost
93
+ oldest.qty -= take
94
+ remaining -= take
95
+ if oldest.qty == 0:
96
+ lots.pop()
97
+
98
+ def catch_up(self, store: EventStore) -> int:
99
+ pending = store.since(self.last_seq)
100
+ for event in pending:
101
+ self.apply(event)
102
+ return len(pending)
103
+
104
+ def value_of(self, sku: str) -> float:
105
+ """Total carrying value of the units still on hand for one SKU."""
106
+ if sku not in self.lots:
107
+ raise UnknownSku(sku)
108
+ return sum(lot.qty * lot.unit_cost for lot in self.lots[sku])
109
+
110
+ def total_value(self) -> float:
111
+ return sum(lot.qty * lot.unit_cost
112
+ for lots in self.lots.values() for lot in lots)
source/corpus/python/ledger/tasks/audit2-04/break/ledger/store.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only event store with snapshot support.
2
+
3
+ The store owns sequence numbering. Nothing else in the package is allowed to
4
+ assign a sequence number, because the ordering guarantee that projections rely
5
+ on is only as good as the single place that hands the numbers out.
6
+ """
7
+ from typing import Dict, Iterable, Iterator, List, Optional
8
+
9
+ from .errors import SequenceError
10
+ from .events import Adjusted, Event, Received, Shipped
11
+
12
+
13
+ class EventStore:
14
+ """Holds every event ever appended, in order."""
15
+
16
+ def __init__(self) -> None:
17
+ self._events: List[Event] = []
18
+ self._next_seq: int = 1
19
+ self._clock: float = 0.0
20
+
21
+ # -- writing ---------------------------------------------------------
22
+
23
+ def _tick(self) -> float:
24
+ self._clock += 1.0
25
+ return self._clock
26
+
27
+ def _append(self, event: Event) -> Event:
28
+ if event.seq != self._next_seq:
29
+ raise SequenceError(
30
+ f"expected seq {self._next_seq}, got {event.seq}")
31
+ self._events.append(event)
32
+ self._next_seq += 1
33
+ return event
34
+
35
+ def receive(self, sku: str, qty: int, unit_cost: float) -> Received:
36
+ """Record stock arriving."""
37
+ if qty <= 0:
38
+ raise ValueError("received quantity must be positive")
39
+ return self._append(
40
+ Received(seq=self._next_seq, ts=self._tick(), sku=sku,
41
+ qty=qty, unit_cost=unit_cost))
42
+
43
+ def ship(self, sku: str, qty: int) -> Shipped:
44
+ """Record stock leaving. Does not itself check availability."""
45
+ if qty <= 0:
46
+ raise ValueError("shipped quantity must be positive")
47
+ return self._append(
48
+ Shipped(seq=self._next_seq, ts=self._tick(), sku=sku, qty=qty))
49
+
50
+ def adjust(self, sku: str, delta: int, reason: str) -> Adjusted:
51
+ """Record a stocktake correction."""
52
+ if delta == 0:
53
+ raise ValueError("adjustment delta must not be zero")
54
+ return self._append(
55
+ Adjusted(seq=self._next_seq, ts=self._tick(), sku=sku,
56
+ delta=delta, reason=reason))
57
+
58
+ # -- reading ---------------------------------------------------------
59
+
60
+ def __len__(self) -> int:
61
+ return len(self._events)
62
+
63
+ def __iter__(self) -> Iterator[Event]:
64
+ return iter(self._events)
65
+
66
+ @property
67
+ def head(self) -> int:
68
+ """Sequence number of the most recent event, or 0 when empty."""
69
+ return self._events[-1].seq if self._events else 0
70
+
71
+ def since(self, seq: int) -> List[Event]:
72
+ """Every event appended strictly after `seq`.
73
+
74
+ A projection resumes by passing the sequence number it last applied, so
75
+ this must be exclusive at the lower bound. Making it inclusive would
76
+ replay one already-applied event on every resume.
77
+ """
78
+ return [e for e in self._events if e.seq > seq]
79
+
80
+ def between(self, low: int, high: int) -> List[Event]:
81
+ """Events with low < seq <= high."""
82
+ return [e for e in self._events if low <= e.seq <= high]
83
+
84
+ def for_sku(self, sku: str) -> List[Event]:
85
+ return [e for e in self._events if e.sku == sku]
86
+
87
+ def skus(self) -> List[str]:
88
+ seen: Dict[str, None] = {}
89
+ for event in self._events:
90
+ seen.setdefault(event.sku, None)
91
+ return list(seen)
92
+
93
+ def replay(self, events: Optional[Iterable[Event]] = None) -> List[Event]:
94
+ """Materialise an event iterable, defaulting to the whole log."""
95
+ return list(self._events if events is None else events)
source/corpus/python/ledger/tasks/audit2-04/task.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 5,
5
+ "compound": true,
6
+ "ingredients": [
7
+ "between-boundary",
8
+ "fifo-lifo"
9
+ ],
10
+ "instruction": "2 findings from this week's triage. They have separate causes and are not related to one another; all 2 need fixing.\n\n1. Our per-period stock report double-counts events on period boundaries.\n Consecutive reports are produced by asking the store for the events between the\n previous report's last sequence number and the current one. An event landing\n exactly on a boundary shows up in both the earlier report and the later one.\n The range is documented as excluding its lower bound and including its upper.\n\n2. Our finance team reports that inventory valuation and cost of goods sold are wrong whenever a SKU has been received at more than one unit cost.\n Concrete case: receive 10 units at 1.00, then 10 units at 3.00, then ship 10 units. Cost of goods sold should be 10.00 and the remaining inventory should be valued at 30.00. We are getting those two numbers the other way round.\n The ledger is documented as valuing inventory on a first-in, first-out basis. Make it do that."
11
+ }
source/corpus/python/ledger/tasks/audit2-04/tests/test_between.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import unittest
3
+
4
+ from ledger import EventStore
5
+
6
+
7
+ def store_with(n):
8
+ store = EventStore()
9
+ for i in range(n):
10
+ store.receive(f"sku{i}", 1, 1.0)
11
+ return store
12
+
13
+
14
+ class TestBetweenIsHalfOpen(unittest.TestCase):
15
+ def test_lower_bound_is_excluded(self):
16
+ self.assertEqual([e.seq for e in store_with(5).between(2, 4)], [3, 4])
17
+
18
+ def test_consecutive_ranges_do_not_overlap(self):
19
+ store = store_with(6)
20
+ first = {e.seq for e in store.between(0, 3)}
21
+ second = {e.seq for e in store.between(3, 6)}
22
+ self.assertEqual(first & second, set())
23
+
24
+ def test_consecutive_ranges_leave_no_gap(self):
25
+ store = store_with(6)
26
+ seen = {e.seq for e in store.between(0, 3)} | {e.seq for e in store.between(3, 6)}
27
+ self.assertEqual(seen, {1, 2, 3, 4, 5, 6})
28
+
29
+ def test_empty_range(self):
30
+ self.assertEqual(store_with(5).between(3, 3), [])
31
+
32
+
33
+ class TestBetweenOtherwiseWorks(unittest.TestCase):
34
+ def test_upper_bound_is_included(self):
35
+ self.assertIn(4, [e.seq for e in store_with(5).between(2, 4)])
36
+
37
+ def test_full_range(self):
38
+ self.assertEqual(len(store_with(5).between(0, 5)), 5)
39
+
40
+ def test_beyond_the_end(self):
41
+ self.assertEqual(len(store_with(3).between(0, 99)), 3)
source/corpus/python/ledger/tasks/audit2-04/tests/test_catch_up.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, StockProjection
4
+ from ledger.errors import SequenceError
5
+
6
+
7
+ class TestIncrementalCatchUp(unittest.TestCase):
8
+ def test_catch_up_twice_across_new_events(self):
9
+ store = EventStore()
10
+ store.receive("widget", 100, 2.50)
11
+ stock = StockProjection()
12
+ stock.catch_up(store)
13
+ store.ship("widget", 30)
14
+ stock.catch_up(store)
15
+ self.assertEqual(stock.on_hand("widget"), 70)
16
+
17
+ def test_catch_up_with_nothing_new_is_a_noop(self):
18
+ store = EventStore()
19
+ store.receive("widget", 10, 1.0)
20
+ stock = StockProjection()
21
+ self.assertEqual(stock.catch_up(store), 1)
22
+ self.assertEqual(stock.catch_up(store), 0)
23
+ self.assertEqual(stock.on_hand("widget"), 10)
24
+
25
+ def test_many_incremental_catch_ups_match_one_big_one(self):
26
+ incremental = StockProjection()
27
+ store = EventStore()
28
+ for i in range(1, 6):
29
+ store.receive("bolt", i * 10, 1.0)
30
+ incremental.catch_up(store)
31
+ oneshot = StockProjection()
32
+ oneshot.catch_up(store)
33
+ self.assertEqual(incremental.levels, oneshot.levels)
34
+ self.assertEqual(incremental.on_hand("bolt"), 150)
35
+
36
+
37
+ class TestOrderingGuaranteesPreserved(unittest.TestCase):
38
+ """Deleting the ordering check would hide the symptom but corrupt totals."""
39
+
40
+ def test_replaying_an_applied_event_is_still_rejected(self):
41
+ store = EventStore()
42
+ store.receive("widget", 5, 1.0)
43
+ stock = StockProjection()
44
+ stock.catch_up(store)
45
+ already_applied = list(store)[0]
46
+ with self.assertRaises(SequenceError):
47
+ stock.apply(already_applied)
48
+
49
+ def test_store_since_is_exclusive_at_the_lower_bound(self):
50
+ store = EventStore()
51
+ store.receive("a", 1, 1.0)
52
+ store.receive("b", 1, 1.0)
53
+ store.receive("c", 1, 1.0)
54
+ self.assertEqual([e.seq for e in store.since(0)], [1, 2, 3])
55
+ self.assertEqual([e.seq for e in store.since(1)], [2, 3])
56
+ self.assertEqual([e.seq for e in store.since(3)], [])
source/corpus/python/ledger/tasks/audit2-04/tests/test_imports.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+
4
+ class TestPackageImports(unittest.TestCase):
5
+ def test_package_imports(self):
6
+ import ledger
7
+ self.assertTrue(hasattr(ledger, "EventStore"))
8
+
9
+ def test_policy_is_usable(self):
10
+ from ledger import EventStore, ReorderPolicy, StockProjection
11
+ store = EventStore()
12
+ store.receive("w", 3, 1.0)
13
+ stock = StockProjection()
14
+ stock.catch_up(store)
15
+ policy = ReorderPolicy({"w": 5}, {"w": 20})
16
+ self.assertEqual([s.sku for s in policy.suggest(stock)], ["w"])
17
+
18
+ def test_projection_still_works(self):
19
+ from ledger import EventStore, StockProjection
20
+ store = EventStore()
21
+ store.receive("w", 7, 1.0)
22
+ stock = StockProjection()
23
+ stock.catch_up(store)
24
+ self.assertEqual(stock.on_hand("w"), 7)
source/corpus/python/ledger/tasks/audit2-04/tests/test_valuation.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, Valuation
4
+
5
+
6
+ def valued(events):
7
+ store = EventStore()
8
+ for kind, sku, *rest in events:
9
+ getattr(store, kind)(sku, *rest)
10
+ valuation = Valuation()
11
+ valuation.catch_up(store)
12
+ return valuation
13
+
14
+
15
+ class TestFifoCostBasis(unittest.TestCase):
16
+ def test_oldest_lot_is_consumed_first(self):
17
+ v = valued([("receive", "w", 10, 1.00),
18
+ ("receive", "w", 10, 3.00),
19
+ ("ship", "w", 10)])
20
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
21
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
22
+
23
+ def test_shipment_spanning_two_lots(self):
24
+ v = valued([("receive", "w", 10, 1.00),
25
+ ("receive", "w", 10, 3.00),
26
+ ("ship", "w", 15)])
27
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10 * 1.00 + 5 * 3.00)
28
+ self.assertAlmostEqual(v.value_of("w"), 5 * 3.00)
29
+
30
+ def test_three_lots_consumed_in_arrival_order(self):
31
+ v = valued([("receive", "w", 5, 1.00),
32
+ ("receive", "w", 5, 2.00),
33
+ ("receive", "w", 5, 4.00),
34
+ ("ship", "w", 12)])
35
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5 * 1.0 + 5 * 2.0 + 2 * 4.0)
36
+ self.assertAlmostEqual(v.value_of("w"), 3 * 4.00)
37
+
38
+ def test_negative_adjustment_also_consumes_oldest_first(self):
39
+ v = valued([("receive", "w", 10, 1.00),
40
+ ("receive", "w", 10, 3.00),
41
+ ("adjust", "w", -10, "stocktake")])
42
+ self.assertAlmostEqual(v.cost_of_goods_sold, 10.00)
43
+ self.assertAlmostEqual(v.value_of("w"), 30.00)
44
+
45
+
46
+ class TestValuationInvariants(unittest.TestCase):
47
+ def test_single_lot_is_unaffected(self):
48
+ v = valued([("receive", "w", 10, 2.00), ("ship", "w", 4)])
49
+ self.assertAlmostEqual(v.cost_of_goods_sold, 8.00)
50
+ self.assertAlmostEqual(v.value_of("w"), 12.00)
51
+
52
+ def test_full_depletion_leaves_no_value(self):
53
+ v = valued([("receive", "w", 5, 1.00),
54
+ ("receive", "w", 5, 9.00),
55
+ ("ship", "w", 10)])
56
+ self.assertAlmostEqual(v.value_of("w"), 0.00)
57
+ self.assertAlmostEqual(v.cost_of_goods_sold, 50.00)
58
+
59
+ def test_separate_skus_do_not_interfere(self):
60
+ v = valued([("receive", "a", 5, 1.00),
61
+ ("receive", "b", 5, 7.00),
62
+ ("ship", "a", 5)])
63
+ self.assertAlmostEqual(v.value_of("b"), 35.00)
64
+ self.assertAlmostEqual(v.cost_of_goods_sold, 5.00)
source/corpus/python/ledger/tasks/audit2-05/break/ledger/policies.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decisions taken on top of the read models.
2
+
3
+ Nothing here touches the event log directly. Policies read a projection and
4
+ return a plan; committing that plan is the caller's business.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .errors import InsufficientStock, UnknownSku
10
+ from .projections import StockProjection
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Warehouse:
15
+ """A stocking location, with a priority used to break ties."""
16
+ name: str
17
+ priority: int
18
+ on_hand: int
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReorderSuggestion:
23
+ sku: str
24
+ order_qty: int
25
+ reason: str
26
+
27
+
28
+ class ReorderPolicy:
29
+ """Suggests replenishment when a SKU falls to or below its threshold.
30
+
31
+ The comparison is deliberately inclusive: a SKU sitting exactly on its
32
+ reorder point has reached it, and waiting for it to drop further is how a
33
+ warehouse runs out during the lead time.
34
+ """
35
+
36
+ def __init__(self, thresholds: Dict[str, int], target: Dict[str, int]):
37
+ self.thresholds = dict(thresholds)
38
+ self.target = dict(target)
39
+
40
+ def threshold_for(self, sku: str) -> int:
41
+ if sku not in self.thresholds:
42
+ raise UnknownSku(sku)
43
+ return self.thresholds[sku]
44
+
45
+ def suggest(self, stock: StockProjection) -> List[ReorderSuggestion]
46
+ """One suggestion per SKU at or below its reorder point."""
47
+ out: List[ReorderSuggestion] = []
48
+ for sku in sorted(self.thresholds):
49
+ level = stock.levels.get(sku, 0)
50
+ threshold = self.thresholds[sku]
51
+ if level <= threshold:
52
+ target = self.target.get(sku, threshold * 2)
53
+ qty = target - level
54
+ if qty > 0:
55
+ out.append(ReorderSuggestion(
56
+ sku=sku, order_qty=qty,
57
+ reason=f"level {level} at or below threshold {threshold}"))
58
+ return out
59
+
60
+
61
+ def allocate(demand: int, warehouses: Sequence[Warehouse]) -> List[Tuple[str, int]]:
62
+ """Split `demand` across warehouses, highest priority first.
63
+
64
+ Ties on priority are broken by name so the result is deterministic. The
65
+ input sequence is never mutated -- callers reuse their warehouse list
66
+ across several allocations and would otherwise see it quietly emptied.
67
+ """
68
+ if demand <= 0:
69
+ raise ValueError("demand must be positive")
70
+
71
+ ordered = sorted(warehouses, key=lambda w: (-w.priority, w.name))
72
+ available = sum(w.on_hand for w in ordered)
73
+ if available < demand:
74
+ raise InsufficientStock("<multiple>", demand, available)
75
+
76
+ plan: List[Tuple[str, int]] = []
77
+ remaining = demand
78
+ for warehouse in ordered:
79
+ if remaining <= 0:
80
+ break
81
+ take = min(warehouse.on_hand, remaining)
82
+ if take > 0:
83
+ plan.append((warehouse.name, take))
84
+ remaining -= take
85
+ return plan
source/corpus/python/ledger/tasks/audit2-05/break/ledger/store.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only event store with snapshot support.
2
+
3
+ The store owns sequence numbering. Nothing else in the package is allowed to
4
+ assign a sequence number, because the ordering guarantee that projections rely
5
+ on is only as good as the single place that hands the numbers out.
6
+ """
7
+ from typing import Dict, Iterable, Iterator, List, Optional
8
+
9
+ from .errors import SequenceError
10
+ from .events import Adjusted, Event, Received, Shipped
11
+
12
+
13
+ class EventStore:
14
+ """Holds every event ever appended, in order."""
15
+
16
+ def __init__(self) -> None:
17
+ self._events: List[Event] = []
18
+ self._next_seq: int = 1
19
+ self._clock: float = 0.0
20
+
21
+ # -- writing ---------------------------------------------------------
22
+
23
+ def _tick(self) -> float:
24
+ self._clock += 1.0
25
+ return self._clock
26
+
27
+ def _append(self, event: Event) -> Event:
28
+ if event.seq != self._next_seq:
29
+ raise SequenceError(
30
+ f"expected seq {self._next_seq}, got {event.seq}")
31
+ self._events.append(event)
32
+ self._next_seq += 1
33
+ return event
34
+
35
+ def receive(self, sku: str, qty: int, unit_cost: float) -> Received:
36
+ """Record stock arriving."""
37
+ if qty <= 0:
38
+ raise ValueError("received quantity must be positive")
39
+ return self._append(
40
+ Received(seq=self._next_seq, ts=self._tick(), sku=sku,
41
+ qty=qty, unit_cost=unit_cost))
42
+
43
+ def ship(self, sku: str, qty: int) -> Shipped:
44
+ """Record stock leaving. Does not itself check availability."""
45
+ if qty <= 0:
46
+ raise ValueError("shipped quantity must be positive")
47
+ return self._append(
48
+ Shipped(seq=self._next_seq, ts=self._tick(), sku=sku, qty=qty))
49
+
50
+ def adjust(self, sku: str, delta: int, reason: str) -> Adjusted:
51
+ """Record a stocktake correction."""
52
+ if delta == 0:
53
+ raise ValueError("adjustment delta must not be zero")
54
+ return self._append(
55
+ Adjusted(seq=self._next_seq, ts=self._tick(), sku=sku,
56
+ delta=delta, reason=reason))
57
+
58
+ # -- reading ---------------------------------------------------------
59
+
60
+ def __len__(self) -> int:
61
+ return len(self._events)
62
+
63
+ def __iter__(self) -> Iterator[Event]:
64
+ return iter(self._events)
65
+
66
+ @property
67
+ def head(self) -> int:
68
+ """Sequence number of the most recent event, or 0 when empty."""
69
+ return self._events[-1].seq if self._events else 0
70
+
71
+ def since(self, seq: int) -> List[Event]:
72
+ """Every event appended strictly after `seq`.
73
+
74
+ A projection resumes by passing the sequence number it last applied, so
75
+ this must be exclusive at the lower bound. Making it inclusive would
76
+ replay one already-applied event on every resume.
77
+ """
78
+ return [e for e in self._events if e.seq > seq]
79
+
80
+ def between(self, low: int, high: int) -> List[Event]:
81
+ """Events with low < seq <= high."""
82
+ return [e for e in self._events if low <= e.seq <= high]
83
+
84
+ def for_sku(self, sku: str) -> List[Event]:
85
+ return [e for e in self._events if e.sku == sku]
86
+
87
+ def skus(self) -> List[str]:
88
+ seen: Dict[str, None] = {}
89
+ for event in self._events:
90
+ seen.setdefault(event.sku, None)
91
+ return list(seen)
92
+
93
+ def replay(self, events: Optional[Iterable[Event]] = None) -> List[Event]:
94
+ """Materialise an event iterable, defaulting to the whole log."""
95
+ return list(self._events if events is None else events)
source/corpus/python/ledger/tasks/audit2-05/task.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "python",
3
+ "category": "logic",
4
+ "difficulty": 5,
5
+ "compound": true,
6
+ "ingredients": [
7
+ "between-boundary",
8
+ "import-syntax"
9
+ ],
10
+ "instruction": "2 findings from this week's triage. They have separate causes and are not related to one another; all 2 need fixing.\n\n1. Our per-period stock report double-counts events on period boundaries.\n Consecutive reports are produced by asking the store for the events between the\n previous report's last sequence number and the current one. An event landing\n exactly on a boundary shows up in both the earlier report and the later one.\n The range is documented as excluding its lower bound and including its upper.\n\n2. The package no longer imports -- `import ledger` fails immediately. Nothing else was changed. Find the syntax error and fix it."
11
+ }
source/corpus/python/ledger/tasks/audit2-05/tests/test_between.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import unittest
3
+
4
+ from ledger import EventStore
5
+
6
+
7
+ def store_with(n):
8
+ store = EventStore()
9
+ for i in range(n):
10
+ store.receive(f"sku{i}", 1, 1.0)
11
+ return store
12
+
13
+
14
+ class TestBetweenIsHalfOpen(unittest.TestCase):
15
+ def test_lower_bound_is_excluded(self):
16
+ self.assertEqual([e.seq for e in store_with(5).between(2, 4)], [3, 4])
17
+
18
+ def test_consecutive_ranges_do_not_overlap(self):
19
+ store = store_with(6)
20
+ first = {e.seq for e in store.between(0, 3)}
21
+ second = {e.seq for e in store.between(3, 6)}
22
+ self.assertEqual(first & second, set())
23
+
24
+ def test_consecutive_ranges_leave_no_gap(self):
25
+ store = store_with(6)
26
+ seen = {e.seq for e in store.between(0, 3)} | {e.seq for e in store.between(3, 6)}
27
+ self.assertEqual(seen, {1, 2, 3, 4, 5, 6})
28
+
29
+ def test_empty_range(self):
30
+ self.assertEqual(store_with(5).between(3, 3), [])
31
+
32
+
33
+ class TestBetweenOtherwiseWorks(unittest.TestCase):
34
+ def test_upper_bound_is_included(self):
35
+ self.assertIn(4, [e.seq for e in store_with(5).between(2, 4)])
36
+
37
+ def test_full_range(self):
38
+ self.assertEqual(len(store_with(5).between(0, 5)), 5)
39
+
40
+ def test_beyond_the_end(self):
41
+ self.assertEqual(len(store_with(3).between(0, 99)), 3)
source/corpus/python/ledger/tasks/audit2-05/tests/test_catch_up.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from ledger import EventStore, StockProjection
4
+ from ledger.errors import SequenceError
5
+
6
+
7
+ class TestIncrementalCatchUp(unittest.TestCase):
8
+ def test_catch_up_twice_across_new_events(self):
9
+ store = EventStore()
10
+ store.receive("widget", 100, 2.50)
11
+ stock = StockProjection()
12
+ stock.catch_up(store)
13
+ store.ship("widget", 30)
14
+ stock.catch_up(store)
15
+ self.assertEqual(stock.on_hand("widget"), 70)
16
+
17
+ def test_catch_up_with_nothing_new_is_a_noop(self):
18
+ store = EventStore()
19
+ store.receive("widget", 10, 1.0)
20
+ stock = StockProjection()
21
+ self.assertEqual(stock.catch_up(store), 1)
22
+ self.assertEqual(stock.catch_up(store), 0)
23
+ self.assertEqual(stock.on_hand("widget"), 10)
24
+
25
+ def test_many_incremental_catch_ups_match_one_big_one(self):
26
+ incremental = StockProjection()
27
+ store = EventStore()
28
+ for i in range(1, 6):
29
+ store.receive("bolt", i * 10, 1.0)
30
+ incremental.catch_up(store)
31
+ oneshot = StockProjection()
32
+ oneshot.catch_up(store)
33
+ self.assertEqual(incremental.levels, oneshot.levels)
34
+ self.assertEqual(incremental.on_hand("bolt"), 150)
35
+
36
+
37
+ class TestOrderingGuaranteesPreserved(unittest.TestCase):
38
+ """Deleting the ordering check would hide the symptom but corrupt totals."""
39
+
40
+ def test_replaying_an_applied_event_is_still_rejected(self):
41
+ store = EventStore()
42
+ store.receive("widget", 5, 1.0)
43
+ stock = StockProjection()
44
+ stock.catch_up(store)
45
+ already_applied = list(store)[0]
46
+ with self.assertRaises(SequenceError):
47
+ stock.apply(already_applied)
48
+
49
+ def test_store_since_is_exclusive_at_the_lower_bound(self):
50
+ store = EventStore()
51
+ store.receive("a", 1, 1.0)
52
+ store.receive("b", 1, 1.0)
53
+ store.receive("c", 1, 1.0)
54
+ self.assertEqual([e.seq for e in store.since(0)], [1, 2, 3])
55
+ self.assertEqual([e.seq for e in store.since(1)], [2, 3])
56
+ self.assertEqual([e.seq for e in store.since(3)], [])