From e0d93a629aea7c1bc3de5c9674464af823aac65c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 30 Oct 2026 23:31:58 +0100 Subject: [PATCH 01/10] e2e: Codex lossy-vs-lossless delta study: task set (7 tasks with acceptance), logging proxy, cell/block runner, index and delta tools Co-Authored-By: Claude Sonnet 5.5 --- .gitattributes | 4 + scripts/e2e/codex/delta/block.py | 135 +++++ scripts/e2e/codex/delta/block.sh | 113 ++++ scripts/e2e/codex/delta/cell.py | 243 ++++++++ scripts/e2e/codex/delta/index.py | 454 ++++++++++++++ scripts/e2e/codex/delta/install.sh | 54 ++ scripts/e2e/codex/delta/jobs/cld-pilot.sh | 11 + scripts/e2e/codex/delta/logproxy.py | 306 ++++++++++ scripts/e2e/codex/delta/taskfile.py | 155 +++++ scripts/e2e/codex/tasks/MANIFEST.sha256 | 203 +++++++ scripts/e2e/codex/tasks/README.md | 56 ++ scripts/e2e/codex/tasks/crm/accept.py | 22 + .../codex/tasks/crm/hidden/crm_acceptance.py | 119 ++++ .../crm/reference/overlay/CODE_REVIEW.md | 78 +++ .../tasks/crm/reference/overlay/README.md | 144 +++++ .../codex/tasks/crm/reference/overlay/db.py | 264 +++++++++ .../tasks/crm/reference/overlay/errors.py | 21 + .../tasks/crm/reference/overlay/handlers.py | 99 ++++ .../tasks/crm/reference/overlay/models.py | 95 +++ .../tasks/crm/reference/overlay/responses.py | 60 ++ .../tasks/crm/reference/overlay/router.py | 176 ++++++ .../tasks/crm/reference/overlay/server.py | 100 ++++ .../crm/reference/overlay/static/index.html | 414 +++++++++++++ .../crm/reference/overlay/tests/__init__.py | 1 + .../tasks/crm/reference/overlay/tests/base.py | 156 +++++ .../reference/overlay/tests/test_activity.py | 110 ++++ .../reference/overlay/tests/test_companies.py | 123 ++++ .../reference/overlay/tests/test_contacts.py | 100 ++++ .../overlay/tests/test_csv_export.py | 81 +++ .../crm/reference/overlay/tests/test_deals.py | 150 +++++ .../overlay/tests/test_live_server.py | 115 ++++ .../crm/reference/overlay/tests/test_notes.py | 65 ++ .../overlay/tests/test_pagination.py | 87 +++ .../reference/overlay/tests/test_pipeline.py | 54 ++ .../overlay/tests/test_robustness.py | 123 ++++ .../overlay/tests/test_server_setup.py | 101 ++++ .../overlay/tests/test_validation.py | 212 +++++++ .../tasks/crm/reference/overlay/validation.py | 98 ++++ scripts/e2e/codex/tasks/crm/task.md | 38 ++ .../e2e/codex/tasks/debuglog-sched/accept.py | 165 ++++++ .../e2e/codex/tasks/debuglog-sched/gen_log.py | 83 +++ .../tasks/debuglog-sched/hidden/evidence.json | 55 ++ .../hidden/orig/sched/__init__.py | 1 + .../debuglog-sched/hidden/orig/sched/clock.py | 24 + .../hidden/orig/sched/dedupe.py | 24 + .../debuglog-sched/hidden/orig/sched/ids.py | 15 + .../debuglog-sched/hidden/orig/sched/lease.py | 38 ++ .../debuglog-sched/hidden/orig/sched/logs.py | 24 + .../hidden/orig/sched/metrics.py | 34 ++ .../debuglog-sched/hidden/orig/sched/model.py | 21 + .../debuglog-sched/hidden/orig/sched/queue.py | 35 ++ .../debuglog-sched/hidden/orig/sched/retry.py | 14 + .../hidden/orig/sched/service.py | 158 +++++ .../debuglog-sched/hidden/orig/sched/sim.py | 270 +++++++++ .../debuglog-sched/hidden/orig/sched/store.py | 24 + .../hidden/orig/sched/worker.py | 55 ++ .../tasks/debuglog-sched/hidden/stress.py | 28 + .../debuglog-sched/hidden/tests/helpers.py | 16 + .../debuglog-sched/hidden/tests/test_ids.py | 27 + .../hidden/tests/test_lease_dedupe.py | 59 ++ .../hidden/tests/test_service.py | 97 +++ .../debuglog-sched/hidden/tests/test_sim.py | 41 ++ .../hidden/tests/test_store_queue.py | 59 ++ .../reference/overlay/FINDINGS.md | 37 ++ .../reference/overlay/sched/ids.py | 12 + .../reference/overlay/sched/store.py | 26 + .../overlay/tests/test_regression.py | 31 + .../tasks/debuglog-sched/seed/run_sim.py | 47 ++ .../debuglog-sched/seed/sched/__init__.py | 1 + .../tasks/debuglog-sched/seed/sched/clock.py | 24 + .../tasks/debuglog-sched/seed/sched/dedupe.py | 24 + .../tasks/debuglog-sched/seed/sched/ids.py | 15 + .../tasks/debuglog-sched/seed/sched/lease.py | 38 ++ .../tasks/debuglog-sched/seed/sched/logs.py | 24 + .../debuglog-sched/seed/sched/metrics.py | 34 ++ .../tasks/debuglog-sched/seed/sched/model.py | 21 + .../tasks/debuglog-sched/seed/sched/queue.py | 35 ++ .../tasks/debuglog-sched/seed/sched/retry.py | 14 + .../debuglog-sched/seed/sched/service.py | 158 +++++ .../tasks/debuglog-sched/seed/sched/sim.py | 270 +++++++++ .../tasks/debuglog-sched/seed/sched/store.py | 24 + .../tasks/debuglog-sched/seed/sched/worker.py | 55 ++ .../debuglog-sched/seed/tests/helpers.py | 16 + .../debuglog-sched/seed/tests/test_ids.py | 27 + .../seed/tests/test_lease_dedupe.py | 59 ++ .../debuglog-sched/seed/tests/test_service.py | 97 +++ .../debuglog-sched/seed/tests/test_sim.py | 41 ++ .../seed/tests/test_store_queue.py | 59 ++ .../e2e/codex/tasks/debuglog-sched/task.md | 39 ++ .../e2e/codex/tasks/feature-query/accept.py | 138 +++++ .../hidden/pristine_tests/test_csv_cli.py | 133 +++++ .../pristine_tests/test_index_storage.py | 72 +++ .../hidden/pristine_tests/test_schema.py | 94 +++ .../hidden/pristine_tests/test_table.py | 175 ++++++ .../feature-query/hidden/test_hidden_spec.py | 555 ++++++++++++++++++ .../feature-query/reference/overlay/README.md | 78 +++ .../reference/overlay/minidb/cli.py | 130 ++++ .../reference/overlay/minidb/query.py | 387 ++++++++++++ .../reference/overlay/minidb/table.py | 199 +++++++ .../reference/overlay/tests/test_query.py | 208 +++++++ .../codex/tasks/feature-query/seed/README.md | 57 ++ .../codex/tasks/feature-query/seed/SPEC.md | 180 ++++++ .../feature-query/seed/minidb/__init__.py | 19 + .../tasks/feature-query/seed/minidb/cli.py | 121 ++++ .../tasks/feature-query/seed/minidb/csvio.py | 63 ++ .../tasks/feature-query/seed/minidb/errors.py | 17 + .../tasks/feature-query/seed/minidb/index.py | 44 ++ .../tasks/feature-query/seed/minidb/schema.py | 132 +++++ .../feature-query/seed/minidb/storage.py | 47 ++ .../tasks/feature-query/seed/minidb/table.py | 196 +++++++ .../feature-query/seed/tests/test_csv_cli.py | 133 +++++ .../seed/tests/test_index_storage.py | 72 +++ .../feature-query/seed/tests/test_schema.py | 94 +++ .../feature-query/seed/tests/test_table.py | 175 ++++++ scripts/e2e/codex/tasks/feature-query/task.md | 38 ++ .../e2e/codex/tasks/fixbug-ledger/accept.py | 90 +++ .../hidden/pristine_tests/helpers.py | 36 ++ .../hidden/pristine_tests/test_accounts.py | 69 +++ .../hidden/pristine_tests/test_calendar.py | 67 +++ .../hidden/pristine_tests/test_cli.py | 66 +++ .../hidden/pristine_tests/test_exporter.py | 53 ++ .../hidden/pristine_tests/test_fx.py | 74 +++ .../hidden/pristine_tests/test_importer.py | 129 ++++ .../hidden/pristine_tests/test_journal.py | 82 +++ .../hidden/pristine_tests/test_money.py | 111 ++++ .../hidden/pristine_tests/test_reports.py | 68 +++ .../hidden/pristine_tests/test_rounding.py | 60 ++ .../pristine_tests/test_transactions.py | 91 +++ .../hidden/pristine_tests/test_utils.py | 53 ++ .../tasks/fixbug-ledger/hidden/test_hidden.py | 254 ++++++++ .../reference/overlay/ledger/accounts.py | 102 ++++ .../reference/overlay/ledger/calendar.py | 78 +++ .../reference/overlay/ledger/importer.py | 162 +++++ .../reference/overlay/ledger/money.py | 137 +++++ .../reference/overlay/ledger/reports.py | 111 ++++ .../reference/overlay/ledger/rounding.py | 48 ++ .../fixbug-ledger/seed/ledger/__init__.py | 17 + .../fixbug-ledger/seed/ledger/accounts.py | 102 ++++ .../fixbug-ledger/seed/ledger/calendar.py | 78 +++ .../tasks/fixbug-ledger/seed/ledger/cli.py | 56 ++ .../fixbug-ledger/seed/ledger/exporter.py | 88 +++ .../tasks/fixbug-ledger/seed/ledger/fx.py | 60 ++ .../fixbug-ledger/seed/ledger/importer.py | 165 ++++++ .../fixbug-ledger/seed/ledger/journal.py | 116 ++++ .../tasks/fixbug-ledger/seed/ledger/money.py | 137 +++++ .../fixbug-ledger/seed/ledger/reports.py | 111 ++++ .../fixbug-ledger/seed/ledger/rounding.py | 48 ++ .../fixbug-ledger/seed/ledger/transactions.py | 116 ++++ .../tasks/fixbug-ledger/seed/ledger/utils.py | 65 ++ .../tasks/fixbug-ledger/seed/tests/helpers.py | 36 ++ .../fixbug-ledger/seed/tests/test_accounts.py | 69 +++ .../fixbug-ledger/seed/tests/test_calendar.py | 67 +++ .../fixbug-ledger/seed/tests/test_cli.py | 66 +++ .../fixbug-ledger/seed/tests/test_exporter.py | 53 ++ .../tasks/fixbug-ledger/seed/tests/test_fx.py | 74 +++ .../fixbug-ledger/seed/tests/test_importer.py | 129 ++++ .../fixbug-ledger/seed/tests/test_journal.py | 82 +++ .../fixbug-ledger/seed/tests/test_money.py | 111 ++++ .../fixbug-ledger/seed/tests/test_reports.py | 68 +++ .../fixbug-ledger/seed/tests/test_rounding.py | 60 ++ .../seed/tests/test_transactions.py | 91 +++ .../fixbug-ledger/seed/tests/test_utils.py | 53 ++ scripts/e2e/codex/tasks/fixbug-ledger/task.md | 38 ++ scripts/e2e/codex/tasks/freeze.py | 13 + .../e2e/codex/tasks/refactor-shop/accept.py | 421 +++++++++++++ .../tasks/refactor-shop/hidden/behaviour.py | 460 +++++++++++++++ .../tasks/refactor-shop/hidden/helpers_h.py | 15 + .../refactor-shop/hidden/tests/helpers.py | 42 ++ .../hidden/tests/test_discounts.py | 64 ++ .../refactor-shop/hidden/tests/test_extras.py | 121 ++++ .../hidden/tests/test_invoices.py | 94 +++ .../hidden/tests/test_orders_customers.py | 123 ++++ .../hidden/tests/test_reports_cli.py | 175 ++++++ .../hidden/tests/test_services.py | 189 ++++++ .../hidden/tests/test_tax_shipping.py | 89 +++ .../reference/overlay/docs/ARCHITECTURE.md | 51 ++ .../reference/overlay/shop/analytics.py | 60 ++ .../reference/overlay/shop/cart.py | 45 ++ .../reference/overlay/shop/cli.py | 89 +++ .../reference/overlay/shop/config.py | 60 ++ .../reference/overlay/shop/customers.py | 79 +++ .../reference/overlay/shop/dates.py | 25 + .../reference/overlay/shop/discounts.py | 19 + .../reference/overlay/shop/export.py | 35 ++ .../reference/overlay/shop/inventory.py | 49 ++ .../reference/overlay/shop/invoices.py | 70 +++ .../reference/overlay/shop/loyalty.py | 16 + .../reference/overlay/shop/notifications.py | 23 + .../reference/overlay/shop/orders.py | 70 +++ .../reference/overlay/shop/pricing.py | 83 +++ .../reference/overlay/shop/products.py | 57 ++ .../reference/overlay/shop/reports.py | 107 ++++ .../reference/overlay/shop/returns.py | 27 + .../reference/overlay/shop/shipping.py | 18 + .../reference/overlay/shop/storage.py | 38 ++ .../reference/overlay/shop/tax.py | 22 + .../reference/overlay/shop/util.py | 8 + .../reference/overlay/shop/validation.py | 35 ++ .../reference/overlay/tests/helpers.py | 42 ++ .../overlay/tests/test_orders_customers.py | 123 ++++ .../tasks/refactor-shop/seed/REFACTOR.md | 157 +++++ .../refactor-shop/seed/docs/ARCHITECTURE.md | 60 ++ .../tasks/refactor-shop/seed/shop/__init__.py | 1 + .../refactor-shop/seed/shop/analytics.py | 55 ++ .../tasks/refactor-shop/seed/shop/cart.py | 50 ++ .../tasks/refactor-shop/seed/shop/cli.py | 89 +++ .../tasks/refactor-shop/seed/shop/currency.py | 13 + .../refactor-shop/seed/shop/customers.py | 89 +++ .../refactor-shop/seed/shop/discounts.py | 86 +++ .../tasks/refactor-shop/seed/shop/export.py | 36 ++ .../refactor-shop/seed/shop/inventory.py | 55 ++ .../tasks/refactor-shop/seed/shop/invoices.py | 125 ++++ .../tasks/refactor-shop/seed/shop/loyalty.py | 24 + .../refactor-shop/seed/shop/notifications.py | 22 + .../tasks/refactor-shop/seed/shop/orders.py | 133 +++++ .../tasks/refactor-shop/seed/shop/products.py | 64 ++ .../tasks/refactor-shop/seed/shop/reports.py | 115 ++++ .../tasks/refactor-shop/seed/shop/returns.py | 30 + .../tasks/refactor-shop/seed/shop/sample.py | 48 ++ .../tasks/refactor-shop/seed/shop/shipping.py | 42 ++ .../tasks/refactor-shop/seed/shop/storage.py | 37 ++ .../tasks/refactor-shop/seed/shop/tax.py | 42 ++ .../tasks/refactor-shop/seed/shop/util.py | 17 + .../refactor-shop/seed/shop/validation.py | 34 ++ .../tasks/refactor-shop/seed/tests/helpers.py | 42 ++ .../seed/tests/test_discounts.py | 64 ++ .../refactor-shop/seed/tests/test_extras.py | 121 ++++ .../refactor-shop/seed/tests/test_invoices.py | 94 +++ .../seed/tests/test_orders_customers.py | 123 ++++ .../seed/tests/test_reports_cli.py | 175 ++++++ .../refactor-shop/seed/tests/test_services.py | 189 ++++++ .../seed/tests/test_tax_shipping.py | 89 +++ scripts/e2e/codex/tasks/refactor-shop/task.md | 35 ++ scripts/e2e/codex/tasks/selftest.py | 79 +++ scripts/e2e/codex/tasks/smoke-mini/accept.py | 85 +++ .../pristine_tests/test_casing_stats.py | 26 + .../hidden/pristine_tests/test_words.py | 25 + .../hidden/pristine_tests/test_wrap.py | 34 ++ .../tasks/smoke-mini/hidden/test_hidden.py | 75 +++ .../reference/overlay/textkit/words.py | 23 + .../reference/overlay/textkit/wrap.py | 36 ++ .../seed/tests/test_casing_stats.py | 26 + .../tasks/smoke-mini/seed/tests/test_words.py | 25 + .../tasks/smoke-mini/seed/tests/test_wrap.py | 34 ++ .../tasks/smoke-mini/seed/textkit/__init__.py | 16 + .../tasks/smoke-mini/seed/textkit/casing.py | 25 + .../tasks/smoke-mini/seed/textkit/stats.py | 21 + .../tasks/smoke-mini/seed/textkit/words.py | 23 + .../tasks/smoke-mini/seed/textkit/wrap.py | 36 ++ scripts/e2e/codex/tasks/smoke-mini/task.md | 20 + scripts/e2e/codex/tasks/ttt/accept.py | 47 ++ .../e2e/codex/tasks/ttt/hidden/check_ttt.mjs | 112 ++++ .../tasks/ttt/reference/overlay/index.html | 402 +++++++++++++ scripts/e2e/codex/tasks/ttt/task.md | 28 + 254 files changed, 21800 insertions(+) create mode 100644 scripts/e2e/codex/delta/block.py create mode 100644 scripts/e2e/codex/delta/block.sh create mode 100644 scripts/e2e/codex/delta/cell.py create mode 100644 scripts/e2e/codex/delta/index.py create mode 100644 scripts/e2e/codex/delta/install.sh create mode 100644 scripts/e2e/codex/delta/jobs/cld-pilot.sh create mode 100644 scripts/e2e/codex/delta/logproxy.py create mode 100644 scripts/e2e/codex/delta/taskfile.py create mode 100644 scripts/e2e/codex/tasks/MANIFEST.sha256 create mode 100644 scripts/e2e/codex/tasks/README.md create mode 100644 scripts/e2e/codex/tasks/crm/accept.py create mode 100644 scripts/e2e/codex/tasks/crm/hidden/crm_acceptance.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/CODE_REVIEW.md create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/README.md create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/db.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/errors.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/handlers.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/models.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/responses.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/router.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/server.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/static/index.html create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/__init__.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/base.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_activity.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_companies.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_contacts.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_csv_export.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_deals.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_live_server.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_notes.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pagination.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pipeline.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_robustness.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_server_setup.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_validation.py create mode 100644 scripts/e2e/codex/tasks/crm/reference/overlay/validation.py create mode 100644 scripts/e2e/codex/tasks/crm/task.md create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/accept.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/gen_log.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/evidence.json create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/__init__.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/clock.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/dedupe.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/ids.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/lease.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/logs.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/metrics.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/model.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/queue.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/retry.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/service.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/sim.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/store.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/worker.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/stress.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_ids.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_lease_dedupe.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_service.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_sim.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_store_queue.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/FINDINGS.md create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/ids.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/store.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/tests/test_regression.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/run_sim.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/__init__.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/clock.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/dedupe.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/ids.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/lease.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/logs.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/metrics.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/model.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/queue.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/retry.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/service.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/sim.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/store.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/sched/worker.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_ids.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_lease_dedupe.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_service.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_sim.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_store_queue.py create mode 100644 scripts/e2e/codex/tasks/debuglog-sched/task.md create mode 100644 scripts/e2e/codex/tasks/feature-query/accept.py create mode 100644 scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_csv_cli.py create mode 100644 scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_index_storage.py create mode 100644 scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_schema.py create mode 100644 scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_table.py create mode 100644 scripts/e2e/codex/tasks/feature-query/hidden/test_hidden_spec.py create mode 100644 scripts/e2e/codex/tasks/feature-query/reference/overlay/README.md create mode 100644 scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/cli.py create mode 100644 scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/query.py create mode 100644 scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/table.py create mode 100644 scripts/e2e/codex/tasks/feature-query/reference/overlay/tests/test_query.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/README.md create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/SPEC.md create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/__init__.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/cli.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/csvio.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/errors.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/index.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/schema.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/storage.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/minidb/table.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/tests/test_csv_cli.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/tests/test_index_storage.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/tests/test_schema.py create mode 100644 scripts/e2e/codex/tasks/feature-query/seed/tests/test_table.py create mode 100644 scripts/e2e/codex/tasks/feature-query/task.md create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/accept.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_accounts.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_calendar.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_cli.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_exporter.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_fx.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_importer.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_journal.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_money.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_reports.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_rounding.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_transactions.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_utils.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/hidden/test_hidden.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/accounts.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/calendar.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/importer.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/money.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/reports.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/rounding.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/__init__.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/accounts.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/calendar.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/cli.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/exporter.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/fx.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/importer.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/journal.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/money.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/reports.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/rounding.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/transactions.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/utils.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_accounts.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_calendar.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_cli.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_exporter.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_fx.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_importer.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_journal.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_money.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_reports.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_rounding.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_transactions.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_utils.py create mode 100644 scripts/e2e/codex/tasks/fixbug-ledger/task.md create mode 100644 scripts/e2e/codex/tasks/freeze.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/accept.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/behaviour.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/helpers_h.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_discounts.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_extras.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_invoices.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_orders_customers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_reports_cli.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_services.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_tax_shipping.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/docs/ARCHITECTURE.md create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/analytics.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cart.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cli.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/config.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/customers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/dates.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/discounts.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/export.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/inventory.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/invoices.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/loyalty.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/notifications.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/orders.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/pricing.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/products.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/reports.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/returns.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/shipping.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/storage.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/tax.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/util.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/validation.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/test_orders_customers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/REFACTOR.md create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/docs/ARCHITECTURE.md create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/__init__.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/analytics.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/cart.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/cli.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/currency.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/customers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/discounts.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/export.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/inventory.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/invoices.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/loyalty.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/notifications.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/orders.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/products.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/reports.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/returns.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/sample.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/shipping.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/storage.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/tax.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/util.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/shop/validation.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/helpers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_discounts.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_extras.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_invoices.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_orders_customers.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_reports_cli.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_services.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_tax_shipping.py create mode 100644 scripts/e2e/codex/tasks/refactor-shop/task.md create mode 100644 scripts/e2e/codex/tasks/selftest.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/accept.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_casing_stats.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_words.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_wrap.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/hidden/test_hidden.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/words.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/wrap.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_casing_stats.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_words.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_wrap.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/textkit/__init__.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/textkit/casing.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/textkit/stats.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/textkit/words.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/seed/textkit/wrap.py create mode 100644 scripts/e2e/codex/tasks/smoke-mini/task.md create mode 100644 scripts/e2e/codex/tasks/ttt/accept.py create mode 100644 scripts/e2e/codex/tasks/ttt/hidden/check_ttt.mjs create mode 100644 scripts/e2e/codex/tasks/ttt/reference/overlay/index.html create mode 100644 scripts/e2e/codex/tasks/ttt/task.md diff --git a/.gitattributes b/.gitattributes index 0f1b7a7d..7df5e12c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,7 @@ # and skips binary-looking files; it only stops CRLF from entering LF files at commit time. crates/**/*.rs text=auto eol=lf scripts/gpu-bringup/**/*.py text=auto eol=lf + +# Codex lossy-delta study: task files are hashed byte for byte (no EOL conversion); the runner scripts are LF. +scripts/e2e/codex/tasks/** -text +scripts/e2e/codex/delta/** text eol=lf diff --git a/scripts/e2e/codex/delta/block.py b/scripts/e2e/codex/delta/block.py new file mode 100644 index 00000000..79af6731 --- /dev/null +++ b/scripts/e2e/codex/delta/block.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Run a list of cells inside ONE running stack (test tooling, stdlib only). Called by block.sh, once the stack is up. + + block.py --variant V3 --tag TAG --cells "fixbug-ledger:1 fixbug-ledger:2 smoke-mini:1:_smoke" --runs-root R --tasks-root T + --upstream http://127.0.0.1:8081 --model qwen-iq3|auto --engine-log PATH --expect-skip on|off --stack-dir D + --codex-bin C --wall-limit 2400 --max-rounds 150 + +A cell token is `task:rep[:set]`; the cell directory is R/[set/]VARIANT/task-rREP. Cells that already hold a cell.json are skipped. +Before the first cell it sends one warm-up request straight to the engine (not part of any cell) and checks that the route tail skip +state the variant is supposed to have is what the engine log says; if not it stops without running a cell. +""" +import argparse +import json +import os +import re +import subprocess +import sys +import time +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +SKIP_ON = re.compile(r"ROUTE_TAIL_SKIP=\d+ is ON|EXPERIMENTAL route tail skip is ON") +SKIP_OFF_OURS = re.compile(r"route tail skip \d+ is OFF") + + +def post(url, body, key, timeout=900): + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, r.read() + + +def read_log(path): + try: + return open(path, "r", errors="replace").read() + except OSError: + return "" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--variant", required=True) + ap.add_argument("--tag", required=True) + ap.add_argument("--cells", required=True) + ap.add_argument("--runs-root", required=True) + ap.add_argument("--tasks-root", required=True) + ap.add_argument("--upstream", required=True) + ap.add_argument("--model", default="auto") + ap.add_argument("--engine-log", required=True) + ap.add_argument("--expect-skip", choices=["on", "off"], required=True) + ap.add_argument("--stack-dir", required=True) + ap.add_argument("--codex-bin", required=True) + ap.add_argument("--wall-limit", type=int, default=2400) + ap.add_argument("--max-rounds", type=int, default=150) + ap.add_argument("--active-dir", required=True) + a = ap.parse_args() + key = os.environ.get("E2E_API_KEY", "none") + model = a.model + if model == "auto": + with urllib.request.urlopen(urllib.request.Request(a.upstream + "/v1/models", headers={"Authorization": "Bearer " + key}), timeout=60) as r: + model = json.loads(r.read())["data"][0]["id"] + blog = open(os.path.join(a.stack_dir, "block.log"), "a", buffering=1) + + def say(msg): + line = "%s %s" % (time.strftime("%H:%M:%SZ", time.gmtime()), msg) + print(line, flush=True) + blog.write(line + "\n") + + # --- warm-up (graph capture, first-request costs), identical for every variant + t0 = time.time() + body = {"model": model, "input": [{"role": "user", "content": [{"type": "input_text", "text": "Reply with the single word OK."}]}], + "max_output_tokens": 48, "temperature": 0, "stream": False} + try: + st, raw = post(a.upstream + "/v1/responses", body, key) + warm = {"status": st, "seconds": round(time.time() - t0, 1), "reply_bytes": len(raw)} + except Exception as e: # noqa: BLE001 + warm = {"status": "error", "error": str(e)[:300]} + say("warm-up: %s" % json.dumps(warm)) + time.sleep(2) + log = read_log(a.engine_log) + on_lines = [l for l in log.splitlines() if SKIP_ON.search(l)] + off_lines = [l for l in log.splitlines() if SKIP_OFF_OURS.search(l)] + skip_state = {"expect": a.expect_skip, "on_lines": on_lines[:3], "off_lines": off_lines[:3]} + ok = bool(on_lines) if a.expect_skip == "on" else not on_lines + say("route tail skip check expect=%s: %s" % (a.expect_skip, "OK" if ok else "MISMATCH")) + for l in (on_lines + off_lines)[:3]: + say(" engine log: " + l.strip()[:300]) + stack = {} + sp = os.path.join(a.stack_dir, "stack.json") + if os.path.exists(sp): + stack = json.load(open(sp)) + stack.update({"variant": a.variant, "tag": a.tag, "upstream_model": model, "warmup": warm, "skip_state": skip_state, + "engine_log": a.engine_log, "block_start_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "uptime_s_at_block": float(open("/proc/uptime").read().split()[0]), + "boot_id": open("/proc/sys/kernel/random/boot_id").read().strip()}) + json.dump(stack, open(sp, "w"), indent=1) + if not ok: + say("STOP: the engine log does not show the expected route tail skip state; no cell is run") + open(os.path.join(a.stack_dir, "BLOCK_FAILED"), "w").write("route tail skip state mismatch\n") + return 5 + import hashlib + h = hashlib.sha256() + with open(a.codex_bin, "rb") as f: + for chunk in iter(lambda: f.read(1 << 22), b""): + h.update(chunk) + codex_sha = h.hexdigest() + for tok in a.cells.split(): + parts = tok.split(":") + task, rep = parts[0], int(parts[1]) + sset = parts[2] if len(parts) > 2 else "" + cell_dir = os.path.join(a.runs_root, sset, a.variant, "%s-r%d" % (task, rep)) + if os.path.exists(os.path.join(cell_dir, "cell.json")): + say("skip %s (done)" % cell_dir) + continue + if os.path.exists(cell_dir): + garbage = cell_dir + ".incomplete-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + os.rename(cell_dir, garbage) + say("renamed an incomplete cell to %s" % garbage) + os.makedirs(os.path.dirname(cell_dir), exist_ok=True) + left = os.path.join(a.active_dir, "ws") + if os.path.exists(left): + moved = os.path.join(a.runs_root, "_incomplete-ws-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime())) + os.rename(left, moved) + say("moved a leftover active workspace to %s" % moved) + say("cell %s" % cell_dir) + cmd = [sys.executable, "-I", os.path.join(HERE, "cell.py"), "--cell-dir", cell_dir, "--variant", a.variant, "--task", task, "--rep", str(rep), + "--tasks-root", a.tasks_root, "--upstream", a.upstream, "--upstream-model", model, "--codex-bin", a.codex_bin, "--codex-sha256", codex_sha, + "--wall-limit", str(a.wall_limit), "--max-rounds", str(a.max_rounds), "--engine-log", a.engine_log, "--stack-meta", sp, "--active-dir", a.active_dir] + r = subprocess.run(cmd, capture_output=True, text=True) + say("cell done rc=%d %s %s" % (r.returncode, r.stdout.strip()[-300:], r.stderr.strip()[-300:])) + time.sleep(5) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/delta/block.sh b/scripts/e2e/codex/delta/block.sh new file mode 100644 index 00000000..05986a8c --- /dev/null +++ b/scripts/e2e/codex/delta/block.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +# One block of the Codex lossy-delta study: start the stack of ONE variant, run a list of cells in it, stop the stack. HOLDER JOB part (ours variants +# need the sealed KAR memfd of the holder; run it from a stub in ~/work/gpu-runs/holder2/jobs/, see delta/jobs/). Test tooling, never in production. +# +# block.sh VARIANT TAG "task:rep[:set] task:rep ..." +# +# V1 vanilla Strata 0.2.6, shipped defaults (route tail skip 7 ON by default, STRATA_PREFILL_CPU_SHARE=auto) +# V2 vanilla Strata 0.2.6, STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 (both lossy defaults off) +# V3 our port (binaries bin-main), shipped profile shape, LELEKA_ROUTE_TAIL_SKIP=7 (EXPERIMENTAL, output changes) +# V4 our port (binaries bin-main), shipped profile shape, route tail skip off (default) +# +# Same machine, same 256k context, same model files, same Codex CLI, same logging proxy (temperature 0 injected for all). +# Takes /data/leleka-e2e/gpu.lock for the whole block (the protocol of the other jobs), waits up to 90 minutes for it. +set -uo pipefail +V=${1:?variant V1..V4}; TAG=${2:?tag}; CELLS=${3:?cells} +ROOT=${CLD_ROOT:-/data/leleka-e2e/codex-lossy-delta} +RUNS=${CLD_RUNS:-/data/leleka-e2e/runs/codex-lossy-delta} +DELTA=$ROOT/delta; TASKS=$ROOT/tasks +CODEX=${CLD_CODEX:-/home/para/work/codex-e2e/bin/codex} +LOCK=/data/leleka-e2e/gpu.lock +WALL=${CLD_WALL_LIMIT:-2400}; CAP=${CLD_MAX_ROUNDS:-150} +A=/home/para/work/leleka/models/leleka-gates/assets +STACK=$RUNS/$V/_stack-$TAG +mkdir -p "$STACK" +log() { echo "[block $V $TAG $(date -u +%T)] $*" | tee -a "$STACK/block.sh.log"; } + +# ---- guards ----------------------------------------------------------------------------------------------------- +[ "$(df --output=avail -B1G /data | tail -1 | tr -d ' ')" -ge 20 ] || { log "refusing: less than 20 GB free on /data"; exit 3; } +python3 -I "$DELTA/taskfile.py" check "$TASKS" >"$STACK/tasks-check.txt" 2>&1 || { log "refusing: task files differ from MANIFEST.sha256"; cat "$STACK/tasks-check.txt"; exit 3; } +[ -x "$CODEX" ] || { log "no codex binary at $CODEX"; exit 3; } +case $V in V1|V2) KIND=vanilla ;; V3|V4) KIND=ours ;; *) log "unknown variant $V"; exit 2 ;; esac + +got=0 +for _ in $(seq 1 1080); do + if mkdir "$LOCK" 2>/dev/null; then echo "codex-lossy-delta $V $TAG $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi + sleep 5 +done +[ $got = 1 ] || { log "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; } +MON=; SAMP= +cleanup() { + [ -n "$MON" ] && kill "$MON" 2>/dev/null + [ -n "$SAMP" ] && kill "$SAMP" 2>/dev/null + if grep -q "codex-lossy-delta $V $TAG" "$LOCK/owner" 2>/dev/null; then rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; fi +} +trap cleanup EXIT +if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then log "GPU busy, giving up"; exit 3; fi + +# ---- monitors (small appends only) ----------------------------------------------------------------------------- +( while true; do echo "$(date +%T),$(nvidia-smi --query-gpu=temperature.gpu,utilization.gpu,power.draw,clocks.sm,memory.used --format=csv,noheader)" >>"$STACK/mon.csv"; sleep 10; done ) & MON=$! +( while sleep 10; do echo "$(date +%T) $(grep -E "MemAvailable|Shmem:|Dirty" /proc/meminfo | tr -s ' ' | tr '\n' ' ') $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory)"; done >>"$STACK/memsample.txt" 2>/dev/null ) & SAMP=$! + +COMMON="--variant $V --tag $TAG --cells \"$CELLS\" --runs-root $RUNS --tasks-root $TASKS --stack-dir $STACK --codex-bin $CODEX --wall-limit $WALL --max-rounds $CAP --active-dir $ROOT/_active" +python3 - "$STACK/stack.json" "$V" "$KIND" <<'PY' +import json, sys, subprocess, os +d = {"variant": sys.argv[2], "kind": sys.argv[3], "host": os.uname().nodename, "kernel": os.uname().release, "env": {}} +for k, v in sorted(os.environ.items()): + if k.startswith(("STRATA_", "LELEKA_")) and "TOKEN" not in k and "KEY" not in k: + d["env"][k] = v +d["gpu"] = subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version,memory.total,clocks.max.sm", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip() +d["codex_version"] = subprocess.run([os.environ.get("CLD_CODEX", "/home/para/work/codex-e2e/bin/codex"), "--version"], capture_output=True, text=True).stdout.strip() +json.dump(d, open(sys.argv[1], "w"), indent=1) +PY + +if [ "$KIND" = ours ]; then + # ---- our port: the shape of the shipped profile rtx5090-32g.json and of the paired A/B jobs (decode/dt/jobs/speedtrain3-ab.sh), no bring-up tracing + export E2E_BIN=$ROOT/bin-main E2E_OUT=$STACK + export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=32819404800 + export E2E_ENGINE_ARGS="--prefix-cache-mib auto --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0" + export E2E_SAMPLE_S=10 LELEKA_CHAIN=all LELEKA_ORIGINAL_SERVE_SEED=off + unset LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF \ + LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_DRAFT_VOCAB \ + LELEKA_BRINGUP_TRACE LELEKA_PREFIX_TRACE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED + if [ "$V" = V3 ]; then export LELEKA_ROUTE_TAIL_SKIP=7; EXPECT=on; else EXPECT=off; fi + { echo "variant=$V tag=$TAG"; date -u +%FT%TZ; free -g | sed -n 2p; uptime + sha256sum "$E2E_BIN"/leleka-inference "$E2E_BIN"/leleka-daemon "$E2E_BIN"/leleka-cli "$E2E_BIN"/strata-next "$A/data/expert-profile.bin" + cat "$ROOT/bin-main/COMMIT.txt" 2>/dev/null + env | grep -E '^(LELEKA_|STRATA_|E2E_)' | grep -v -E 'TOKEN|KEY' | sort; } >"$STACK/env-arm.txt" + export CLD_CODEX=$CODEX + export E2E_RUN_CMD="python3 -I $DELTA/block.py $COMMON --upstream http://127.0.0.1:8081 --model qwen-iq3 --engine-log $STACK/inference.log --expect-skip $EXPECT" + bash "$ROOT/run-e2e/run-e2e.sh" 2>&1 | grep -a -v '^$' | cut -c1-300 | tee -a "$STACK/block.sh.log" + RC=${PIPESTATUS[0]} + log "run-e2e rc=$RC" +else + # ---- vanilla Strata 0.2.6 (launcher ~/work/vanilla-strata/control, engine 0.1.50), as in the paired A/B jobs; launcher state redirected into the block directory + export XDG_CONFIG_HOME=$STACK/xdg-config XDG_STATE_HOME=$STACK/xdg-state + mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME" + cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/" + unset STRATA_ROUTE_TAIL_SKIP STRATA_PREFILL_CPU_SHARE STRATA_DECODE_TIMING STRATA_VERIFY_PROFILE + if [ "$V" = V2 ]; then export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; EXPECT=off; else EXPECT=on; fi + S=$HOME/work/vanilla-strata/control/bin/strata + { echo "variant=$V tag=$TAG"; date -u +%FT%TZ; free -g | sed -n 2p; uptime + sha256sum "$HOME/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata"; cat "$HOME/work/vanilla-strata/control/VERSION" "$HOME/work/vanilla-strata/control/COMMIT" 2>/dev/null + env | grep -E '^(STRATA_|LELEKA_)' | sort; } >"$STACK/env-arm.txt" + cd "$HOME/work/vanilla-strata/control" + T0=$(date +%s) + timeout 2400 "$S" launch --model iq3_s --family qwen --model-path "$A/model" --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes >"$STACK/launch.out" 2>&1 + echo "launch_rc=$? ready_wall_s=$(( $(date +%s) - T0 ))" >>"$STACK/env-arm.txt" + ENGLOG=$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log + if curl -fs http://127.0.0.1:8090/v1/models >"$STACK/models.json"; then + export CLD_CODEX=$CODEX E2E_API_KEY=none + python3 -I "$DELTA/block.py" --variant "$V" --tag "$TAG" --cells "$CELLS" --runs-root "$RUNS" --tasks-root "$TASKS" --stack-dir "$STACK" --codex-bin "$CODEX" \ + --wall-limit "$WALL" --max-rounds "$CAP" --active-dir "$ROOT/_active" --upstream http://127.0.0.1:8090 --model auto --engine-log "$ENGLOG" --expect-skip "$EXPECT" 2>&1 | tee -a "$STACK/block.sh.log" + RC=${PIPESTATUS[0]} + cp "$ENGLOG" "$STACK/engine.log" + else + log "vanilla did not become ready"; RC=6 + fi + "$S" launch --stop >>"$STACK/launch.out" 2>&1 + sleep 8 + log "vanilla block rc=$RC" +fi +date -u +%FT%TZ >"$STACK/block.end" +exit "${RC:-0}" diff --git a/scripts/e2e/codex/delta/cell.py b/scripts/e2e/codex/delta/cell.py new file mode 100644 index 00000000..300a03e9 --- /dev/null +++ b/scripts/e2e/codex/delta/cell.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Run ONE cell (variant, task, repeat) of the Codex lossy-delta study against an already running stack (test tooling, stdlib only). + + cell.py --cell-dir D --variant V1 --task fixbug-ledger --rep 1 --tasks-root TASKS --upstream http://127.0.0.1:8081 + --upstream-model qwen-iq3 --codex-bin CODEX --wall-limit 2400 --max-rounds 150 [--engine-log PATH] [--stack-meta FILE] + +Refuses to start when the task md / seed / acceptance files differ from MANIFEST.sha256. Writes into D: + workspace/ the final workspace (seed copied byte for byte before the run, then whatever Codex did) + codex-home/ CODEX_HOME of the run: config.toml and sessions/**/rollout-*.jsonl (Codex's own record of the session) + codex-events.jsonl `codex exec --json` events with the wall-clock time they were read (t_unix_ms) + codex.err Codex stderr + proxy/ logproxy output: rounds.jsonl and one gzip file per request and response (every byte Codex sent and received) + engine-slice.log the part of the engine log written during the cell (when --engine-log is given) + acceptance.log, acceptance.rc, workspace.sha256, prompt.txt, cell.json (metadata and outcome) +""" +import argparse +import json +import os +import shutil +import signal +import socket +import subprocess +import sys +import threading +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import taskfile # noqa: E402 + + +def utc(): + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cell-dir", required=True) + ap.add_argument("--variant", required=True) + ap.add_argument("--task", required=True) + ap.add_argument("--rep", type=int, required=True) + ap.add_argument("--tasks-root", required=True) + ap.add_argument("--upstream", required=True) + ap.add_argument("--upstream-model", required=True) + ap.add_argument("--codex-bin", required=True) + ap.add_argument("--codex-sha256", default="") + ap.add_argument("--wall-limit", type=int, default=2400) + ap.add_argument("--max-rounds", type=int, default=150) + ap.add_argument("--effort", default="medium") + ap.add_argument("--temperature", type=float, default=0.0) + ap.add_argument("--engine-log", default="") + ap.add_argument("--stack-meta", default="") + ap.add_argument("--active-dir", default="", help="directory in which the workspace lives while Codex runs (moved into the cell afterwards)") + a = ap.parse_args() + + cell = os.path.abspath(a.cell_dir) + if os.path.exists(os.path.join(cell, "cell.json")): + print("refusing: %s already holds a finished cell" % cell, file=sys.stderr) + return 3 + # --- the task files must be byte-identical to the frozen manifest + problems = taskfile.check(a.tasks_root, [a.task]) + if problems: + print("refusing to start: task %s differs from MANIFEST.sha256:\n %s" % (a.task, "\n ".join(problems[:10])), file=sys.stderr) + return 3 + meta = taskfile.read_task(a.tasks_root, a.task) + prompt = meta["prompt"] + tdir = os.path.join(a.tasks_root, a.task) + os.makedirs(cell, exist_ok=True) + final_ws = os.path.join(cell, "workspace") + active = os.path.abspath(a.active_dir) if a.active_dir else cell + ws = os.path.join(active, "ws") if a.active_dir else final_ws + if os.path.exists(ws) or os.path.exists(final_ws): + print("refusing: workspace exists", file=sys.stderr) + return 3 + os.makedirs(active, exist_ok=True) + seed = os.path.join(tdir, "seed") + if os.path.isdir(seed): + shutil.copytree(seed, ws) + else: + os.makedirs(ws) + for rel, sha, _n in meta["externals"]: + src = os.path.join(a.tasks_root, "_external", rel) + if not os.path.isfile(src) or taskfile.sha256_file(src) != sha: + print("refusing: external seed file %s missing or differs (%s)" % (rel, src), file=sys.stderr) + shutil.rmtree(ws, ignore_errors=True) + return 3 + shutil.copy(src, os.path.join(ws, rel)) + want = [l for l in open(os.path.join(a.tasks_root, "MANIFEST.sha256")).read().splitlines() if l.startswith("SEEDTREE %s " % a.task)] + have = taskfile.tree_digest(taskfile.workspace_lines(ws)) + if not want or want[0].split()[2] != have: + print("refusing: the installed workspace digest %s differs from the manifest (%s)" % (have, want), file=sys.stderr) + shutil.rmtree(ws, ignore_errors=True) + return 3 + seed_digest = have + with open(os.path.join(cell, "prompt.txt"), "w", encoding="utf-8", newline="") as f: + f.write(prompt) + + # --- Codex home with the config (same template for all variants; the model name Codex sees is fixed) + port = free_port() + chome = os.path.join(cell, "codex-home") + os.makedirs(chome, mode=0o700) + tmpl = open(os.path.join(HERE, "..", "config.toml.tmpl"), encoding="utf-8").read() + cfg = tmpl.replace("@MODEL@", "qwen-local").replace("@BASE_URL@", "http://127.0.0.1:%d" % port).replace("@EFFORT@", a.effort) + open(os.path.join(chome, "config.toml"), "w", encoding="utf-8").write(cfg) + + # --- logging proxy + pdir = os.path.join(cell, "proxy") + os.makedirs(pdir) + perr = open(os.path.join(cell, "proxy.err"), "w") + proxy = subprocess.Popen([sys.executable, os.path.join(HERE, "logproxy.py"), "--listen", "127.0.0.1:%d" % port, "--upstream", a.upstream, + "--out", pdir, "--temperature", str(a.temperature), "--model-map", "qwen-local=" + a.upstream_model, + "--max-rounds", str(a.max_rounds)], stdout=perr, stderr=perr) + for _ in range(100): + try: + socket.create_connection(("127.0.0.1", port), timeout=0.2).close() + break + except OSError: + time.sleep(0.1) + + elog_start = os.path.getsize(a.engine_log) if a.engine_log and os.path.exists(a.engine_log) else 0 + env = dict(os.environ) + env.update({"CODEX_HOME": chome}) + if "E2E_API_KEY" not in env: + env["E2E_API_KEY"] = "none" + cmd = [a.codex_bin, "exec", "--json", "--skip-git-repo-check", "-C", ws, prompt] + t0 = time.time() + start_utc = utc() + events = open(os.path.join(cell, "codex-events.jsonl"), "w", encoding="utf-8", buffering=1) + errf = open(os.path.join(cell, "codex.err"), "w") + p = subprocess.Popen(cmd, cwd=ws, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=errf, start_new_session=True) + final_msg = {"text": ""} + + def reader(): + for raw in p.stdout: + line = raw.decode("utf-8", errors="replace").rstrip("\n") + tms = int(time.time() * 1000) + try: + d = json.loads(line) + if isinstance(d, dict): + d["t_unix_ms"] = tms + it = d.get("item") or {} + if d.get("type") == "item.completed" and it.get("type") == "agent_message": + final_msg["text"] = it.get("text") or "" + line = json.dumps(d, separators=(",", ":")) + else: + line = json.dumps({"t_unix_ms": tms, "value": d}) + except ValueError: + line = json.dumps({"t_unix_ms": tms, "raw": line}) + events.write(line + "\n") + + th = threading.Thread(target=reader, daemon=True) + th.start() + termination = "exited" + cap_path = os.path.join(pdir, "cap.reached") + while True: + rc = p.poll() + if rc is not None: + break + if time.time() - t0 > a.wall_limit: + termination = "wall_limit" + elif os.path.exists(cap_path): + termination = "round_cap" + if termination != "exited": + try: + os.killpg(p.pid, signal.SIGTERM) + except OSError: + pass + for _ in range(20): + if p.poll() is not None: + break + time.sleep(0.5) + if p.poll() is None: + try: + os.killpg(p.pid, signal.SIGKILL) + except OSError: + pass + rc = p.wait() + break + time.sleep(0.5) + th.join(timeout=10) + wall = time.time() - t0 + end_utc = utc() + events.close() + errf.close() + # a stray child of the agent (a server it started) must not outlive the cell + try: + os.killpg(p.pid, signal.SIGKILL) + except OSError: + pass + time.sleep(1) + proxy.terminate() + try: + proxy.wait(10) + except subprocess.TimeoutExpired: + proxy.kill() + perr.close() + + if a.engine_log and os.path.exists(a.engine_log): + with open(a.engine_log, "rb") as f: + f.seek(elog_start) + data = f.read() + with open(os.path.join(cell, "engine-slice.log"), "wb") as f: + f.write(data) + + if ws != final_ws: + shutil.move(ws, final_ws) + ws = final_ws + # --- objective acceptance (on the final workspace; the script copies it first) + acc_rc = -1 + try: + r = subprocess.run([sys.executable, os.path.join(tdir, "accept.py"), ws], capture_output=True, text=True, timeout=900) + acc_rc = r.returncode + open(os.path.join(cell, "acceptance.log"), "w", encoding="utf-8").write(r.stdout + ("\n--- stderr ---\n" + r.stderr if r.stderr.strip() else "")) + except subprocess.TimeoutExpired: + open(os.path.join(cell, "acceptance.log"), "w").write("acceptance timed out\n") + open(os.path.join(cell, "acceptance.rc"), "w").write("%d\n" % acc_rc) + open(os.path.join(cell, "workspace.sha256"), "w").write("\n".join(taskfile.workspace_lines(ws)) + "\n") + + stack = {} + if a.stack_meta and os.path.exists(a.stack_meta): + stack = json.load(open(a.stack_meta)) + info = {"variant": a.variant, "task": a.task, "rep": a.rep, "start_utc": start_utc, "end_utc": end_utc, "wall_s": round(wall, 1), + "codex_rc": rc, "termination": termination, "accepted": acc_rc == 0, "acceptance_rc": acc_rc, + "wall_limit_s": a.wall_limit, "max_rounds_cap": a.max_rounds, "effort": a.effort, "temperature_injected": a.temperature, + "prompt_sha256": taskfile.sha256_text(prompt), "seed_digest": seed_digest, "codex_bin": a.codex_bin, "codex_sha256": a.codex_sha256, + "upstream": a.upstream, "upstream_model": a.upstream_model, "engine_log_start_offset": elog_start, "active_workspace": os.path.join(active, "ws") if a.active_dir else final_ws, + "tasks_manifest_sha256": taskfile.sha256_file(os.path.join(a.tasks_root, "MANIFEST.sha256")), + "final_message_tail": final_msg["text"][-800:], "stack": stack} + tmp = os.path.join(cell, "cell.json.part") + json.dump(info, open(tmp, "w"), indent=1) + os.replace(tmp, os.path.join(cell, "cell.json")) + print("cell %s %s r%d: codex_rc=%s %s wall=%.0fs accepted=%s" % (a.variant, a.task, a.rep, rc, termination, wall, acc_rc == 0), flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/delta/index.py b/scripts/e2e/codex/delta/index.py new file mode 100644 index 00000000..3f727786 --- /dev/null +++ b/scripts/e2e/codex/delta/index.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +"""Index, transcripts and deltas of the Codex lossy-delta runs (test tooling, stdlib only, Python 3.9+). + + index.py RUNS_ROOT [--out DIR] [--no-transcripts] + +Reads every cell under RUNS_ROOT (`[set/]V?/-r/cell.json`) and writes into --out (default RUNS_ROOT/_index): + index.csv one row per cell (variant, task, repeat, rounds, accepted, token distributions, wall, tok/s, skip counters, final message tail, paths) + rounds.csv one row per model request (input / cached / output / reasoning tokens, times, status, the actions the model took) + index.md the same as a table, the per-task lossy-minus-lossless round deltas (V1-V2 vanilla, V3-V4 ours, cross deltas), the spread across repeats, + the first point where lossy and lossless sessions diverge, and the greedy-determinism check (same variant, repeat 1 against repeat 2) +and, unless --no-transcripts, CELL/transcript.md: the session in reading order (every round: new tool outputs, the model's reasoning, calls, messages). +It makes NO quality judgement; it only computes numbers and points to where to read. +""" +import csv +import glob +import gzip +import json +import math +import os +import re +import statistics +import sys + +LABEL = {"V1": "vanilla lossy", "V2": "vanilla lossless", "V3": "ours lossy", "V4": "ours lossless"} +PAIRS = [("V1", "V2", "vanilla"), ("V3", "V4", "ours")] +CROSS = [("V3", "V1", "lossy: ours minus vanilla"), ("V4", "V2", "lossless: ours minus vanilla")] + + +# ---------------------------------------------------------------------------------------------------------------- reading +def jl(path): + out = [] + try: + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + except OSError: + pass + return out + + +def gz_json(path): + try: + return json.loads(gzip.open(path, "rb").read().decode("utf-8", errors="replace")) + except (OSError, ValueError): + return None + + +def gz_text(path): + try: + return gzip.open(path, "rb").read().decode("utf-8", errors="replace") + except OSError: + return "" + + +def find_cells(root): + cells = [] + for cj in sorted(glob.glob(os.path.join(root, "**", "cell.json"), recursive=True)): + d = os.path.dirname(cj) + if "/_index" in d.replace(os.sep, "/"): + continue + rel = os.path.relpath(d, root).replace(os.sep, "/") + parts = rel.split("/") + sset = "/".join(parts[:-2]) + cells.append((sset, d, json.load(open(cj)))) + return cells + + +def sse_items(text): + """Output items (from response.output_item.done) and the terminal response object of an SSE body.""" + items, final = [], None + for line in text.splitlines(): + if line.startswith("data:"): + try: + d = json.loads(line[5:].strip()) + except ValueError: + continue + t = d.get("type") + if t == "response.output_item.done": + items.append(d.get("item") or {}) + elif t in ("response.completed", "response.incomplete", "response.failed"): + final = d.get("response") or d + if not items and final: + items = final.get("output") or [] + if not items and text.lstrip().startswith("{"): + try: + items = json.loads(text).get("output") or [] + except ValueError: + pass + return items, final + + +def action_of(item): + t = item.get("type") + if t == "function_call": + return "call %s %s" % (item.get("name"), (item.get("arguments") or "").strip()) + if t == "message": + txt = "".join(c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict)) + return "message %s" % txt.strip() + if t == "reasoning": + return None # reasoning text is not an action + return "%s %s" % (t, json.dumps(item, sort_keys=True)[:200]) + + +def item_text(item): + t = item.get("type") + if t == "function_call": + return "CALL %s(%s)" % (item.get("name"), item.get("arguments")) + if t == "message": + return "MESSAGE: " + "".join(c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict)) + if t == "reasoning": + summ = " ".join((s.get("text") or "") for s in item.get("summary") or [] if isinstance(s, dict)) + cont = " ".join((s.get("text") or "") for s in item.get("content") or [] if isinstance(s, dict)) + enc = len(item.get("encrypted_content") or "") + return "REASONING: %s%s%s" % (summ, cont, (" [encrypted %d bytes]" % enc) if enc else "") + if t == "function_call_output": + out = item.get("output") + return "TOOL OUTPUT (%s): %s" % (item.get("call_id"), out if isinstance(out, str) else json.dumps(out)) + if t == "message" or item.get("role"): + c = item.get("content") + if isinstance(c, list): + c = "".join(x.get("text") or "" for x in c if isinstance(x, dict)) + return "%s: %s" % (item.get("role"), c) + return json.dumps(item)[:1000] + + +# ---------------------------------------------------------------------------------------------------------------- one cell +def cell_rounds(d): + return [r for r in jl(os.path.join(d, "proxy", "rounds.jsonl")) if r.get("round")] + + +def counters(d, info): + """Route tail skip counters of the cell from the engine log slice (ours: per request lines; vanilla: cumulative lines).""" + out = {"skip_entries": None, "skip_experts": None, "skip_source": ""} + p = os.path.join(d, "engine-slice.log") + try: + text = open(p, errors="replace").read() + except OSError: + return out + if re.search(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", text): + # cumulative since the engine start: the value at the start of the cell is the last one logged before it (read from the stack log) + base_e = base_x = 0 + stack_log = (info.get("stack") or {}).get("engine_log") + off = info.get("engine_log_start_offset") or 0 + if stack_log and os.path.exists(stack_log) and off: + with open(stack_log, "rb") as f: + head = f.read(off).decode("utf-8", errors="replace") + prev = re.findall(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", head) + if prev: + base_x, base_e = int(prev[-1][0]), int(prev[-1][1]) + last_x, last_e = [(int(a), int(b)) for a, b in re.findall(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", text)][-1] + out.update({"skip_entries": last_e - base_e, "skip_experts": last_x - base_x, "skip_source": "vanilla cumulative delta"}) + return out + ours = re.findall(r"expert tier:.*?route tail skip (\d+) entries / (\d+) experts", text) + tiers = re.findall(r"leleka-serve expert tier:", text) + if ours: + ents = [int(a) for a, _ in ours] + exps = [int(b) for _, b in ours] + out.update({"skip_entries": sum(ents), "skip_experts": sum(exps), "skip_source": "ours: sum of %d per-request lines (of %d tier lines; last %d/%d)" % (len(ours), len(tiers), ents[-1], exps[-1])}) + elif tiers: + out.update({"skip_entries": 0, "skip_experts": 0, "skip_source": "ours: %d tier lines, none with a tail skip" % len(tiers)}) + return out + + +def pct(xs, p): + if not xs: + return None + xs = sorted(xs) + return xs[min(len(xs) - 1, int(p * len(xs)))] + + +def summarize(sset, d, info): + rs = cell_rounds(d) + ok = [r for r in rs if (r.get("resp") or {}).get("terminal") == "response.completed"] + inp = [(r.get("resp") or {}).get("input_tokens") for r in rs] + outt = [(r.get("resp") or {}).get("output_tokens") for r in rs] + inp = [x for x in inp if isinstance(x, int)] + outt = [x for x in outt if isinstance(x, int)] + dec_ms = sum((r.get("t_end_ms") or 0) - (r.get("t_first_byte_ms") or r.get("t_end_ms") or 0) for r in ok) + tot_out = sum(outt) + model_ms = sum((r.get("t_end_ms") or 0) - (r.get("t_start_ms") or 0) for r in rs) + events = jl(os.path.join(d, "codex-events.jsonl")) + tool_calls = sum(1 for e in events if e.get("type") == "item.completed" and (e.get("item") or {}).get("type") == "command_execution") + c = counters(d, info) + row = { + "set": sset, "variant": info["variant"], "label": LABEL.get(info["variant"], ""), "task": info["task"], "rep": info["rep"], + "rounds": len(rs), "rounds_completed": len(ok), "rounds_failed": len(rs) - len(ok), + "accepted": "yes" if info.get("accepted") else "no", "termination": info.get("termination"), "codex_rc": info.get("codex_rc"), + "wall_s": info.get("wall_s"), "model_s": round(model_ms / 1000, 1), + "in_tokens_total": sum(inp), "out_tokens_total": tot_out, "ctx_peak": max(inp) if inp else None, + "in_per_round_p50": pct(inp, .5), "in_per_round_p90": pct(inp, .9), "out_per_round_p50": pct(outt, .5), "out_per_round_p90": pct(outt, .9), "out_per_round_max": max(outt) if outt else None, + "cached_tokens_total": sum((r.get("resp") or {}).get("cached_tokens") or 0 for r in rs), + "decode_tok_s": round(tot_out / (dec_ms / 1000), 1) if dec_ms > 0 else None, + "tool_calls": tool_calls, "skip_entries": c["skip_entries"], "skip_experts": c["skip_experts"], "skip_source": c["skip_source"], + "final_message_tail": re.sub(r"\s+", " ", info.get("final_message_tail") or "")[-240:], + "cell_dir": d, "session_log": os.path.join(d, "proxy", "rounds.jsonl"), "transcript": os.path.join(d, "transcript.md"), + "codex_rollout": (glob.glob(os.path.join(d, "codex-home", "sessions", "**", "rollout-*.jsonl"), recursive=True) or [""])[0], + "start_utc": info.get("start_utc"), "uptime_s_at_block": (info.get("stack") or {}).get("uptime_s_at_block"), + } + return row, rs + + +# ---------------------------------------------------------------------------------------------------------------- transcript +def build_actions(d, rs): + """Per round: (new input items, output items, terminal). Reads the gzip request / response bodies.""" + acts, prev_in, prev_out = [], None, [] + for r in rs: + s = "%04d" % r["seq"] + req = gz_json(os.path.join(d, "proxy", "rounds", s + ".req.json.gz")) or {} + inp = req.get("input") if isinstance(req.get("input"), list) else [] + items, final = sse_items(gz_text(os.path.join(d, "proxy", "rounds", s + ".resp.sse.gz"))) + if prev_in is None: + new = inp + note = "first request" + else: + base = len(prev_in) + len(prev_out) + if len(inp) >= base and inp[:len(prev_in)] == prev_in: + new = inp[base:] + note = "" + else: + new = inp + note = "history was rewritten (retry or compaction): all %d input items shown" % len(inp) + acts.append({"seq": r["seq"], "round": r["round"], "req": req, "new": new, "note": note, "out": items, "final": final, "rec": r}) + prev_in, prev_out = inp, items + return acts + + +def write_transcript(d, acts, info): + lines = [] + lines.append("# %s %s r%s (%s)" % (info["variant"], info["task"], info["rep"], LABEL.get(info["variant"], ""))) + lines.append("accepted=%s termination=%s wall=%ss rounds=%d" % (info.get("accepted"), info.get("termination"), info.get("wall_s"), len(acts))) + lines.append("") + for a in acts: + rec, u = a["rec"], (a["rec"].get("resp") or {}) + lines.append("## round %d (proxy seq %d) status=%s in=%s cached=%s out=%s reasoning=%s t=%s..%s ms" % ( + a["round"], a["seq"], rec.get("status"), u.get("input_tokens"), u.get("cached_tokens"), u.get("output_tokens"), u.get("reasoning_tokens"), + rec.get("t_start_ms"), rec.get("t_end_ms"))) + if a["note"]: + lines.append("(%s)" % a["note"]) + for it in a["new"]: + txt = item_text(it) if isinstance(it, dict) else str(it) + if a["round"] == 1 and isinstance(it, dict) and it.get("role") in ("developer", "system") and len(txt) > 3000: + txt = txt[:600] + " ... [%d chars, cut: see the request file]" % len(txt) + elif len(txt) > 2500: + txt = txt[:2000] + "\n... [%d chars cut: full text in proxy/rounds/%04d.req.json.gz]" % (len(txt), a["seq"]) + lines.append("IN " + txt.replace("\n", "\n ")) + for it in a["out"]: + lines.append("OUT " + item_text(it).replace("\n", "\n ")) + if rec.get("outcome") not in (None, "ok") or u.get("error"): + lines.append("!! outcome=%s error=%s" % (rec.get("outcome"), json.dumps(u.get("error"))[:300])) + lines.append("") + text = "\n".join(lines) + "\n" + p = os.path.join(d, "transcript.md") + with open(p + ".part", "w", encoding="utf-8") as f: + f.write(text) + os.replace(p + ".part", p) + # line numbers of every round's OUT lines, for the divergence report + idx = {} + for n, line in enumerate(text.splitlines(), 1): + m = re.match(r"## round (\d+) ", line) + if m: + idx[int(m.group(1))] = n + return idx + + +def action_seq(a): + return [x for x in (action_of(i) for i in a["out"]) if x] + + +def first_divergence(acts_a, acts_b): + """-> (round, action_a, action_b) of the first round whose actions differ, or None when the common prefix is identical.""" + for k in range(min(len(acts_a), len(acts_b))): + sa, sb = action_seq(acts_a[k]), action_seq(acts_b[k]) + if sa != sb: + return k + 1, sa, sb + if len(acts_a) != len(acts_b): + k = min(len(acts_a), len(acts_b)) + return k + 1, ["(session A ends)"] if len(acts_a) == k else action_seq(acts_a[k]), ["(session B ends)"] if len(acts_b) == k else action_seq(acts_b[k]) + return None + + +# ---------------------------------------------------------------------------------------------------------------- statistics +def mean(xs): + return sum(xs) / len(xs) if xs else float("nan") + + +def sd(xs): + return statistics.stdev(xs) if len(xs) > 1 else float("nan") + + +def fmt(x, nd=1): + return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else ("%.*f" % (nd, x)) + + +def rounds_by(rows): + g = {} + for r in rows: + if r["set"] == "_smoke": + continue + g.setdefault((r["task"], r["variant"]), []).append(r) + return g + + +def delta_table(rows, tasks, pairs, title): + g = rounds_by(rows) + out = ["### " + title, "", "| task | A | B | n(A) | n(B) | rounds A (mean, sd, min-max) | rounds B (mean, sd, min-max) | A-B rounds | A/B-1 | completed A | completed B | paired A-B by repeat |", "|---|---|---|---|---|---|---|---|---|---|---|---|"] + allrel = {} + for (a, b, name) in pairs: + for t in tasks: + ra, rb = g.get((t, a), []), g.get((t, b), []) + if not ra or not rb: + continue + xa, xb = [r["rounds"] for r in ra], [r["rounds"] for r in rb] + ca = sum(1 for r in ra if r["accepted"] == "yes") + cb = sum(1 for r in rb if r["accepted"] == "yes") + by_b = {r["rep"]: r["rounds"] for r in rb} + paired = ["r%s:%+d" % (r["rep"], r["rounds"] - by_b[r["rep"]]) for r in ra if r["rep"] in by_b] + rel = mean(xa) / mean(xb) - 1 if mean(xb) else float("nan") + allrel.setdefault(name, []).append(rel) + out.append("| %s | %s | %s | %d | %d | %s, %s, %d-%d | %s, %s, %d-%d | %s | %s | %d/%d | %d/%d | %s |" % ( + t, a, b, len(xa), len(xb), fmt(mean(xa)), fmt(sd(xa)), min(xa), max(xa), fmt(mean(xb)), fmt(sd(xb)), min(xb), max(xb), + "%+.1f" % (mean(xa) - mean(xb)), "%+.1f%%" % (100 * rel), ca, len(ra), cb, len(rb), " ".join(paired))) + out.append("") + for name, rels in allrel.items(): + rels = [x for x in rels if not math.isnan(x)] + if rels: + out.append("%s: mean of the per-task relative deltas %+.1f%% (sd across tasks %s, %d tasks); the per-task rows above are the evidence, this line is only a summary." % ( + name, 100 * mean(rels), fmt(100 * sd(rels)) + "%", len(rels))) + out.append("") + return out + + +def noise_section(rows, tasks): + g = rounds_by(rows) + cvs = [] + out = ["### Run-to-run noise of the round count (same variant, same task, different repeat)", "", "| task | variant | n | rounds | mean | sd | CV |", "|---|---|---|---|---|---|---|"] + for t in tasks: + for v in ("V1", "V2", "V3", "V4"): + rs = g.get((t, v), []) + if len(rs) >= 2: + x = [r["rounds"] for r in rs] + cv = sd(x) / mean(x) if mean(x) else float("nan") + cvs.append(cv) + out.append("| %s | %s | %d | %s | %s | %s | %s |" % (t, v, len(x), " ".join(map(str, x)), fmt(mean(x)), fmt(sd(x)), fmt(100 * cv) + "%")) + out.append("") + cvs = [c for c in cvs if not math.isnan(c)] + if cvs: + cv = math.sqrt(mean([c * c for c in cvs])) + out.append("Pooled CV of rounds across the cells with >= 2 repeats: %.0f%% (%d cells)." % (100 * cv, len(cvs))) + out.append("Resolvable relative difference of two cell means with n repeats each (two-sided alpha 0.05, power 0.8, pooled CV; normal approximation 2.8 * CV * sqrt(2/n)):") + for n in (2, 3, 4, 6, 9, 12): + out.append("- n=%d: about %.0f%%" % (n, 280 * cv * math.sqrt(2.0 / n))) + out.append("") + return out + + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith("--")] + root = os.path.abspath(args[0]) + outdir = os.path.abspath(sys.argv[sys.argv.index("--out") + 1]) if "--out" in sys.argv else os.path.join(root, "_index") + do_tr = "--no-transcripts" not in sys.argv + os.makedirs(outdir, exist_ok=True) + rows, per_cell, round_rows = [], {}, [] + for sset, d, info in find_cells(root): + row, rs = summarize(sset, d, info) + rows.append(row) + acts = build_actions(d, rs) + if do_tr: + idx = write_transcript(d, acts, info) + else: + idx = {} + per_cell[(sset, info["variant"], info["task"], info["rep"])] = (d, acts, idx, row) + for a in acts: + rec, u = a["rec"], a["rec"].get("resp") or {} + ttft = (rec.get("t_first_byte_ms") or 0) - (rec.get("t_start_ms") or 0) + dec = (rec.get("t_end_ms") or 0) - (rec.get("t_first_byte_ms") or rec.get("t_end_ms") or 0) + round_rows.append({"set": sset, "variant": info["variant"], "task": info["task"], "rep": info["rep"], "round": a["round"], "seq": a["seq"], + "status": rec.get("status"), "terminal": u.get("terminal"), "input_tokens": u.get("input_tokens"), "cached_tokens": u.get("cached_tokens"), + "output_tokens": u.get("output_tokens"), "reasoning_tokens": u.get("reasoning_tokens"), "ttft_ms": ttft, "decode_ms": dec, + "tok_s": round(u["output_tokens"] / (dec / 1000), 1) if u.get("output_tokens") and dec > 0 else None, + "actions": " | ".join(x[:120].replace("\n", " ") for x in action_seq(a))}) + rows.sort(key=lambda r: (r["set"], r["task"], r["variant"], r["rep"])) + if rows: + with open(os.path.join(outdir, "index.csv"), "w", newline="", encoding="utf-8") as f: + w = csv.DictWriter(f, fieldnames=list(rows[0].keys())) + w.writeheader() + w.writerows(rows) + if round_rows: + with open(os.path.join(outdir, "rounds.csv"), "w", newline="", encoding="utf-8") as f: + w = csv.DictWriter(f, fieldnames=list(round_rows[0].keys())) + w.writeheader() + w.writerows(round_rows) + + tasks = sorted(set(r["task"] for r in rows if r["set"] != "_smoke")) + md = ["# Codex lossy-delta: index of %d cells" % len(rows), "", "Variants: " + "; ".join("%s = %s" % (k, v) for k, v in LABEL.items()), ""] + md += ["## Cells", "", "| set | variant | task | rep | rounds (ok/failed) | accepted | termination | wall s | ctx peak | in/round p50 | out/round p50 (max) | decode tok/s | skip entries | final message tail | transcript |", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + for r in rows: + md.append("| %s | %s | %s | %s | %d (%d/%d) | %s | %s | %s | %s | %s | %s (%s) | %s | %s | %s | %s |" % ( + r["set"] or "-", r["variant"], r["task"], r["rep"], r["rounds"], r["rounds_completed"], r["rounds_failed"], r["accepted"], r["termination"], fmt(r["wall_s"], 0), + r["ctx_peak"], r["in_per_round_p50"], r["out_per_round_p50"], r["out_per_round_max"], fmt(r["decode_tok_s"]), r["skip_entries"], + r["final_message_tail"][-100:].replace("|", "/"), r["transcript"])) + md.append("") + md += ["## Round deltas (lossy minus lossless; A-B rows are computed from the cells above, the matrix set only)", ""] + md += delta_table(rows, tasks, PAIRS, "Lossy minus lossless per engine: V1-V2 (vanilla), V3-V4 (ours)") + md += delta_table(rows, tasks, CROSS, "Cross deltas: ours minus vanilla (V3-V1 lossy, V4-V2 lossless)") + md += noise_section(rows, tasks) + + md += ["## First divergence of lossy and lossless sessions (same task and repeat; first round whose actions differ)", "", + "Actions = the model's tool calls (name + arguments) and messages of that round; reasoning text is not compared. Lines refer to each cell's transcript.md.", "", + "| task | engine | rep | lossy cell | lossless cell | first differing round | transcript line (lossy / lossless) | lossy action | lossless action |", "|---|---|---|---|---|---|---|---|---|"] + for t in tasks: + for (lossy, lossless, name) in PAIRS: + for key, (d, acts, idx, row) in sorted(per_cell.items()): + sset, v, tt, rep = key + if v != lossy or tt != t or sset == "_smoke": + continue + other = per_cell.get((sset, lossless, t, rep)) + if not other: + continue + dv = first_divergence(acts, other[1]) + if dv is None: + md.append("| %s | %s | %d | %s | %s | none: identical actions in all %d common rounds | - | - | - |" % (t, name, rep, d, other[0], min(len(acts), len(other[1])))) + else: + k, sa, sb = dv + md.append("| %s | %s | %d | %s | %s | %d | %s / %s | %s | %s |" % (t, name, rep, d, other[0], k, idx.get(k, "-"), other[2].get(k, "-"), + (" ; ".join(sa))[:160].replace("|", "/"), (" ; ".join(sb))[:160].replace("|", "/"))) + md += ["", "## Determinism check (same variant, same task, repeat i against repeat j; greedy decoding is requested but the adaptive expert tier and the prefix cache state are not bit-exact run to run)", "", + "| variant | task | reps | first differing round | rounds A / B | accepted A / B |", "|---|---|---|---|---|---|"] + by_vt = {} + for key in per_cell: + sset, v, t, rep = key + if sset != "_smoke": + by_vt.setdefault((v, t), []).append(rep) + for (v, t), reps in sorted(by_vt.items()): + reps = sorted(reps) + for i in range(len(reps)): + for j in range(i + 1, len(reps)): + a = per_cell[("", v, t, reps[i])] if ("", v, t, reps[i]) in per_cell else None + b = per_cell[("", v, t, reps[j])] if ("", v, t, reps[j]) in per_cell else None + if not a or not b: + continue + dv = first_divergence(a[1], b[1]) + md.append("| %s | %s | r%d vs r%d | %s | %d / %d | %s / %s |" % (v, t, reps[i], reps[j], "identical" if dv is None else dv[0], len(a[1]), len(b[1]), a[3]["accepted"], b[3]["accepted"])) + with open(os.path.join(outdir, "index.md"), "w", encoding="utf-8") as f: + f.write("\n".join(md) + "\n") + print("wrote %d cells, %d rounds into %s" % (len(rows), len(round_rows), outdir)) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/codex/delta/install.sh b/scripts/e2e/codex/delta/install.sh new file mode 100644 index 00000000..f02e797e --- /dev/null +++ b/scripts/e2e/codex/delta/install.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Install the Codex lossy-delta study on rnr5090 from the laptop worktree (small writes only: scripts and task files, no model data). +# +# bash scripts/e2e/codex/delta/install.sh +# +# Server layout (all inside the work folder ~/work/leleka = /data/leleka-e2e): +# codex-lossy-delta/tasks/ frozen task set (read-only), without reference/ solutions; tasks/_external/ holds the third-party seed file +# codex-lossy-delta/delta/ runner scripts (read-only) +# codex-lossy-delta/run-e2e/ run-e2e.sh (state dir patched to codex-lossy-delta/w) + helpers +# codex-lossy-delta/config.toml.tmpl, INSTALL.sha256 +# codex-lossy-delta/bin-main/ our binaries (uploaded separately, see COMMIT.txt) +# Re-running replaces the scripts; nothing is hard-deleted (earlier installs go to ~/work/leleka/garbage/ with a line in LOG.txt). +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +CODEX_DIR=$(cd "$HERE/.." && pwd) # scripts/e2e/codex +E2E_DIR=$(cd "$CODEX_DIR/.." && pwd) # scripts/e2e +python3 "$CODEX_DIR/tasks/freeze.py" >/dev/null +python3 "$HERE/taskfile.py" check "$CODEX_DIR/tasks" >/dev/null +R=work/leleka/codex-lossy-delta +STAGE=$R/_stage +ssh rnr5090 bash -s "$R" <<'REMOTE' +set -euo pipefail +R=$1 +mkdir -p "$HOME/$R"; cd "$HOME/$R" +chmod -R u+w tasks delta run-e2e config.toml.tmpl 2>/dev/null || true +if [ -e _stage ]; then G=$HOME/work/leleka/garbage/codex-lossy-delta-stage-$(date -u +%Y%m%dT%H%M%S); mkdir -p "$G"; mv _stage "$G/"; echo "$(date -u +%FT%TZ) codex-lossy-delta: leftover _stage moved to $G" >> "$HOME/work/leleka/garbage/LOG.txt"; fi +mkdir -p _stage/delta _stage/tasks _stage/run-e2e +REMOTE +tar -C "$CODEX_DIR" --exclude=__pycache__ --exclude='reference' --exclude='selftest.py' -cf - tasks | ssh rnr5090 "tar -xf - -C $STAGE/tasks --strip-components=1" +tar -C "$CODEX_DIR" --exclude=__pycache__ -cf - delta | ssh rnr5090 "tar -xf - -C $STAGE/delta --strip-components=1" +tar -C "$E2E_DIR" -cf - run-e2e.sh sample_env.sh status_writer.sh | ssh rnr5090 "tar -xf - -C $STAGE/run-e2e" +scp -q "$CODEX_DIR/config.toml.tmpl" "rnr5090:$STAGE/config.toml.tmpl" +ssh rnr5090 bash -s "$R" <<'REMOTE' +set -euo pipefail +R=$1 +cd "$HOME/$R/_stage" +sed -i 's|^W=.*|W=/data/leleka-e2e/codex-lossy-delta/w|' run-e2e/run-e2e.sh +grep -n '^W=' run-e2e/run-e2e.sh +mkdir -p tasks/_external +cp "$HOME/work/codex-e2e/vendor/three.module.min.js" tasks/_external/ +python3 -I delta/taskfile.py check tasks +cd "$HOME/$R" +G=$HOME/work/leleka/garbage/codex-lossy-delta-prev-$(date -u +%Y%m%dT%H%M%S) +mkdir -p "$G" +for x in delta tasks run-e2e config.toml.tmpl; do [ -e "$x" ] && mv "$x" "$G/"; done +echo "$(date -u +%FT%TZ) codex-lossy-delta: previous install moved to $G" >> "$HOME/work/leleka/garbage/LOG.txt" +mv _stage/delta delta; mv _stage/tasks tasks; mv _stage/run-e2e run-e2e; mv _stage/config.toml.tmpl config.toml.tmpl; rmdir _stage +mkdir -p w _active +chmod -R a-w tasks delta run-e2e config.toml.tmpl +( find tasks delta run-e2e -type f -print0 | sort -z | xargs -0 sha256sum; sha256sum config.toml.tmpl ) > INSTALL.sha256.new +mv -f INSTALL.sha256.new INSTALL.sha256 +wc -l INSTALL.sha256 +REMOTE +echo installed diff --git a/scripts/e2e/codex/delta/jobs/cld-pilot.sh b/scripts/e2e/codex/delta/jobs/cld-pilot.sh new file mode 100644 index 00000000..87bdcf8e --- /dev/null +++ b/scripts/e2e/codex/delta/jobs/cld-pilot.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Holder job: smoke (smoke-mini once) + determinism pilot (fixbug-ledger twice) for the four variants, one stack start per variant. +# The fixbug-ledger cells are matrix cells (repeats 1 and 2 of the study); smoke-mini goes to the set _smoke. +# Install: stub ~/work/gpu-runs/holder2/jobs/cld-pilot.sh = `exec bash /data/leleka-e2e/codex-lossy-delta/delta/jobs/cld-pilot.sh`. +set -uo pipefail +B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh +for V in V1 V2 V3 V4; do + bash "$B" "$V" pilot "smoke-mini:1:_smoke fixbug-ledger:1 fixbug-ledger:2" + echo "=== block $V done rc=$? $(date -u +%FT%TZ)" + sleep 20 +done diff --git a/scripts/e2e/codex/delta/logproxy.py b/scripts/e2e/codex/delta/logproxy.py new file mode 100644 index 00000000..b9c327f2 --- /dev/null +++ b/scripts/e2e/codex/delta/logproxy.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Logging reverse proxy between the Codex CLI and a Responses endpoint (test tooling, stdlib only, Python 3.9+). + + logproxy.py --listen 127.0.0.1:PORT --upstream http://127.0.0.1:8081 --out DIR + [--temperature 0] [--model-map LOCAL=UPSTREAM] [--max-rounds N] + +The same proxy sits in front of vanilla Strata and of our stack, so every request and response is captured identically: + + DIR/rounds.jsonl one line per HTTP request: seq, path, status, timings (ms since proxy start), sizes, sha256 of the body Codex sent + and of the body forwarded, the sampling fields forwarded, the usage and the output item summary of the response + DIR/rounds/NNNN.req.json.gz the request body exactly as Codex sent it (gzip) + DIR/rounds/NNNN.fwd.json.gz only when the proxy changed the body (temperature injection, model name mapping): the body forwarded + DIR/rounds/NNNN.resp.sse.gz the response body exactly as received from the engine (SSE stream or JSON), gzip + DIR/cap.reached created when more than --max-rounds POST .../responses requests arrived (later ones get a 503, nothing reaches the engine) + +Round = a POST whose path ends in /responses (a model request). Authorization is forwarded and never logged. +The injected `temperature` makes the sampling identical for every variant (Codex sends none; vanilla Strata would otherwise use the model card's +sampling, our server greedy). +""" +import argparse +import gzip +import hashlib +import http.client +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlsplit + +HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "host", "content-length"} +SECRET_HEADERS = {"authorization", "x-api-key", "cookie", "proxy-authorization"} + + +class State: + def __init__(self, args): + self.args = args + u = urlsplit(args.upstream) + self.up_host, self.up_port = u.hostname, u.port or 80 + self.out = args.out + os.makedirs(os.path.join(self.out, "rounds"), exist_ok=True) + self.log = open(os.path.join(self.out, "rounds.jsonl"), "a", encoding="utf-8", buffering=1) + self.lock = threading.Lock() + self.seq = 0 + self.rounds = 0 + self.t0 = time.time() + self.model_map = dict(m.split("=", 1) for m in args.model_map) + + def ms(self): + return int((time.time() - self.t0) * 1000) + + def next_seq(self, is_round): + with self.lock: + self.seq += 1 + if is_round: + self.rounds += 1 + return self.seq, self.rounds + + def write(self, rec): + with self.lock: + self.log.write(json.dumps(rec, separators=(",", ":"), ensure_ascii=False) + "\n") + + +def gz_write(path, data): + tmp = path + ".part" + with open(tmp, "wb") as f: + f.write(gzip.compress(data, 6, mtime=0)) + os.replace(tmp, path) + + +def summarize_sse(body): + """Usage, status and a short summary of the output items from an SSE body or a JSON body.""" + out = {"events": 0} + text = body.decode("utf-8", errors="replace") + final = None + items = [] + if text.lstrip().startswith("{"): + try: + final = json.loads(text) + except ValueError: + final = None + else: + ev = None + for line in text.splitlines(): + if line.startswith("event:"): + ev = line[6:].strip() + elif line.startswith("data:"): + out["events"] += 1 + try: + d = json.loads(line[5:].strip()) + except ValueError: + continue + t = d.get("type") or ev + if t in ("response.completed", "response.incomplete", "response.failed"): + final = d.get("response") or d + out["terminal"] = t + elif t == "response.output_item.done": + items.append(d.get("item") or {}) + elif t == "error": + out["error"] = d + if final: + out["status"] = final.get("status") + u = final.get("usage") or {} + out["input_tokens"] = u.get("input_tokens") + out["output_tokens"] = u.get("output_tokens") + out["cached_tokens"] = (u.get("input_tokens_details") or {}).get("cached_tokens") + out["reasoning_tokens"] = (u.get("output_tokens_details") or {}).get("reasoning_tokens") + if final.get("error"): + out["error"] = final["error"] + if final.get("incomplete_details"): + out["incomplete"] = final["incomplete_details"] + if not items: + items = final.get("output") or [] + summ = [] + for it in items: + k = {"type": it.get("type")} + if it.get("type") == "function_call": + k["name"] = it.get("name") + k["arg_bytes"] = len(it.get("arguments") or "") + elif it.get("type") == "message": + k["text_bytes"] = sum(len(c.get("text") or "") for c in it.get("content") or [] if isinstance(c, dict)) + summ.append(k) + out["items"] = summ + return out + + +def summarize_req(body, headers): + out = {"content_encoding": headers.get("content-encoding"), "content_type": headers.get("content-type")} + if headers.get("content-encoding"): + return out + try: + d = json.loads(body) + except ValueError: + out["not_json"] = True + return out + if not isinstance(d, dict): + return out + inp = d.get("input") + out.update({"model": d.get("model"), "stream": d.get("stream"), "n_input_items": len(inp) if isinstance(inp, list) else None, + "n_tools": len(d.get("tools") or []), "previous_response_id": d.get("previous_response_id"), + "temperature": d.get("temperature"), "top_p": d.get("top_p"), "max_output_tokens": d.get("max_output_tokens"), + "reasoning": d.get("reasoning"), "tool_choice": d.get("tool_choice"), "parallel_tool_calls": d.get("parallel_tool_calls"), + "store": d.get("store"), "keys": sorted(d.keys())}) + if isinstance(inp, list): + last = inp[-1] if inp else {} + out["last_item_type"] = last.get("type") or last.get("role") if isinstance(last, dict) else None + return out + + +def make_handler(st): + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + server_version = "logproxy/1" + + def log_message(self, *a): + pass + + def _body(self): + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + data = b"" + while True: + size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16) + if size == 0: + self.rfile.readline() + break + data += self.rfile.read(size) + self.rfile.readline() + return data + n = int(self.headers.get("Content-Length") or 0) + return self.rfile.read(n) if n else b"" + + def _handle(self): + t_start = st.ms() + body = self._body() + path = self.path + is_round = self.command == "POST" and urlsplit(path).path.endswith("/responses") + seq, rounds = st.next_seq(is_round) + sname = "%04d" % seq + rec = {"seq": seq, "method": self.command, "path": path, "round": rounds if is_round else None, "t_start_ms": t_start, + "req_bytes": len(body), "req_sha256": hashlib.sha256(body).hexdigest(), + "req": summarize_req(body, {k.lower(): v for k, v in self.headers.items()}), + "req_headers": {k: v for k, v in self.headers.items() if k.lower() not in SECRET_HEADERS}} + if body: + gz_write(os.path.join(st.out, "rounds", sname + ".req.json.gz"), body) + if is_round and st.args.max_rounds and rounds > st.args.max_rounds: + open(os.path.join(st.out, "cap.reached"), "w").write("round %d > cap %d\n" % (rounds, st.args.max_rounds)) + msg = json.dumps({"error": {"message": "round cap reached", "type": "server_error", "code": "round_cap"}}).encode() + self.send_response(503) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(msg))) + self.end_headers() + self.wfile.write(msg) + rec.update({"status": 503, "outcome": "cap", "t_end_ms": st.ms()}) + st.write(rec) + return + fwd = body + if is_round and not self.headers.get("Content-Encoding"): + try: + d = json.loads(body) + except ValueError: + d = None + if isinstance(d, dict): + changed = False + if st.args.temperature is not None and "temperature" not in d: + d["temperature"] = st.args.temperature + changed = True + if d.get("model") in st.model_map: + d["model"] = st.model_map[d["model"]] + changed = True + if changed: + fwd = json.dumps(d, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + gz_write(os.path.join(st.out, "rounds", sname + ".fwd.json.gz"), fwd) + rec["fwd_sha256"] = hashlib.sha256(fwd).hexdigest() + rec["fwd_sampling"] = {"temperature": d.get("temperature"), "model": d.get("model")} + elif is_round: + rec["fwd_note"] = "body has a Content-Encoding; forwarded unchanged (no temperature injected)" + headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP} + headers["Host"] = "%s:%d" % (st.up_host, st.up_port) + headers["Content-Length"] = str(len(fwd)) + resp_buf = bytearray() + t_first = None + outcome = "ok" + conn = http.client.HTTPConnection(st.up_host, st.up_port, timeout=None) + try: + conn.request(self.command, path, body=fwd if (fwd or self.command in ("POST", "PUT")) else None, headers=headers) + resp = conn.getresponse() + rec["status"] = resp.status + rh = {k: v for k, v in resp.getheaders()} + rec["resp_headers"] = {k: v for k, v in rh.items() if k.lower() not in SECRET_HEADERS} + self.send_response(resp.status) + streaming = "text/event-stream" in (rh.get("Content-Type") or rh.get("content-type") or "").lower() or resp.getheader("Content-Length") is None + for k, v in resp.getheaders(): + if k.lower() in HOP or k.lower() in ("date", "server"): + continue + self.send_header(k, v) + if streaming: + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + while True: + chunk = resp.read1(65536) if streaming else resp.read(65536) + if not chunk: + break + if t_first is None: + t_first = st.ms() + resp_buf += chunk + if streaming: + self.wfile.write(b"%x\r\n" % len(chunk) + chunk + b"\r\n") + else: + self.wfile.write(chunk) + self.wfile.flush() + if streaming: + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError): + outcome = "client_disconnected" + except Exception as e: # upstream failure + outcome = "proxy_error: %s: %s" % (type(e).__name__, e) + if "status" not in rec: + msg = json.dumps({"error": {"message": outcome, "type": "server_error"}}).encode() + try: + self.send_response(502) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(msg))) + self.end_headers() + self.wfile.write(msg) + except OSError: + pass + rec["status"] = 502 + finally: + conn.close() + rec.update({"t_first_byte_ms": t_first, "t_end_ms": st.ms(), "resp_bytes": len(resp_buf), "outcome": outcome}) + if resp_buf: + gz_write(os.path.join(st.out, "rounds", sname + ".resp.sse.gz"), bytes(resp_buf)) + rec["resp"] = summarize_sse(bytes(resp_buf)) + st.write(rec) + if outcome != "ok": + self.close_connection = True + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = _handle + + return H + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--listen", required=True) + ap.add_argument("--upstream", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--temperature", type=float, default=None) + ap.add_argument("--model-map", action="append", default=[]) + ap.add_argument("--max-rounds", type=int, default=0) + args = ap.parse_args() + st = State(args) + host, port = args.listen.rsplit(":", 1) + srv = ThreadingHTTPServer((host, int(port)), make_handler(st)) + srv.daemon_threads = True + print("logproxy listening on %s -> %s, out %s" % (args.listen, args.upstream, args.out), flush=True) + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/codex/delta/taskfile.py b/scripts/e2e/codex/delta/taskfile.py new file mode 100644 index 00000000..5cd70942 --- /dev/null +++ b/scripts/e2e/codex/delta/taskfile.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Task files of the Codex lossy-delta study: parse task.md, hash trees, manifest (test tooling, stdlib only, Python 3.9+). + + taskfile.py prompt TASKS_ROOT ID print the exact prompt text (no trailing newline) + taskfile.py check TASKS_ROOT [ID ...] verify MANIFEST.sha256 against the files; exit 1 on any difference + +Manifest lines: ` /` for every file under tasks// (sorted), `EXTERNAL `, +`PROMPT `, `SEEDTREE ` (digest of the workspace the runner builds: seed/ plus external files) +and `TASK `. +""" +import hashlib +import os +import re +import sys + +BEGIN = "" +END = "" +SKIP_DIRS = {"__pycache__"} + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def sha256_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def read_task(tasks_root, task_id): + """-> dict(front matter fields, prompt, externals=[(relpath, sha256, bytes)])""" + with open(os.path.join(tasks_root, task_id, "task.md"), encoding="utf-8", newline="") as f: + text = f.read() + if "\r" in text: + raise ValueError("%s/task.md contains CR characters" % task_id) + m = re.match(r"---\n(.*?)\n---\n", text, re.S) + if not m: + raise ValueError("%s/task.md has no front matter" % task_id) + meta = {} + for line in m.group(1).splitlines(): + if ":" in line: + k, v = line.split(":", 1) + meta[k.strip()] = v.strip() + if text.count(BEGIN) != 1 or text.count(END) != 1: + raise ValueError("%s/task.md needs exactly one prompt block" % task_id) + body = text.split(BEGIN, 1)[1].split(END, 1)[0] + meta["prompt"] = body.strip("\n") + ext = [] + if "## External seed files" in text: + for line in text.split("## External seed files", 1)[1].splitlines(): + parts = line.split() + if len(parts) == 3 and re.fullmatch(r"[0-9a-f]{64}", parts[1]): + ext.append((parts[0], parts[1], int(parts[2]))) + meta["externals"] = ext + if meta.get("id") != task_id: + raise ValueError("%s/task.md has id %r" % (task_id, meta.get("id"))) + return meta + + +def task_ids(tasks_root): + return sorted(d for d in os.listdir(tasks_root) if os.path.isfile(os.path.join(tasks_root, d, "task.md"))) + + +def task_files(tasks_root, task_id, reference=False): + """Files of a task directory. The reference solution (reference/) is not installed on the server (the agent could find it), so it is not part of + the checked file list; `reference=True` lists only it.""" + base = os.path.join(tasks_root, task_id) + out = [] + for root, dirs, files in os.walk(base): + dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS) + in_ref = os.path.relpath(root, base).replace(os.sep, "/").split("/")[0] == "reference" + if in_ref != reference: + continue + for n in sorted(files): + if n.endswith(".pyc"): + continue + p = os.path.join(root, n) + out.append((os.path.relpath(p, tasks_root).replace(os.sep, "/"), p)) + return sorted(out) + + +def tree_digest(lines): + return hashlib.sha256(("\n".join(lines) + "\n").encode()).hexdigest() + + +def seed_tree_lines(seed_dir, externals): + """Lines `relpath sha256` of a workspace: the files of seed_dir plus the external files (sha256 from the task).""" + lines = [] + if os.path.isdir(seed_dir): + for root, dirs, files in os.walk(seed_dir): + dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS) + for n in sorted(files): + p = os.path.join(root, n) + lines.append("%s %s" % (os.path.relpath(p, seed_dir).replace(os.sep, "/"), sha256_file(p))) + for rel, sha, _n in externals: + lines.append("%s %s" % (rel, sha)) + return sorted(lines) + + +def workspace_lines(ws): + return seed_tree_lines(ws, []) + + +def manifest_lines(tasks_root, ids=None): + out = [] + for tid in ids or task_ids(tasks_root): + meta = read_task(tasks_root, tid) + file_lines = [] + for rel, p in task_files(tasks_root, tid): + file_lines.append("%s %s" % (sha256_file(p), rel)) + out.extend(file_lines) + for rel, sha, n in meta["externals"]: + out.append("EXTERNAL %s %s %s %d" % (tid, rel, sha, n)) + out.append("PROMPT %s %s" % (tid, sha256_text(meta["prompt"]))) + out.append("SEEDTREE %s %s" % (tid, tree_digest(seed_tree_lines(os.path.join(tasks_root, tid, "seed"), meta["externals"])))) + out.append("TASK %s %s" % (tid, tree_digest(file_lines))) + ref = ["%s %s" % (sha256_file(p), rel) for rel, p in task_files(tasks_root, tid, reference=True)] + out.append("REFERENCE %s %s" % (tid, tree_digest(ref))) + return out + + +def _task_of(line): + parts = line.split() + if parts and parts[0] in ("EXTERNAL", "PROMPT", "SEEDTREE", "TASK", "REFERENCE"): + return parts[1] + return parts[-1].split("/", 1)[0] if parts else "" + + +def check(tasks_root, ids=None): + """-> list of problems (empty = the files match MANIFEST.sha256).""" + mpath = os.path.join(tasks_root, "MANIFEST.sha256") + if not os.path.isfile(mpath): + return ["MANIFEST.sha256 missing"] + recorded = [l for l in open(mpath, encoding="utf-8").read().splitlines() if l] + ids = ids or task_ids(tasks_root) + want = set(l for l in manifest_lines(tasks_root, ids) if not l.startswith("REFERENCE ")) + have = set(l for l in recorded if _task_of(l) in ids and not l.startswith("REFERENCE ") and "/reference/" not in l) + return ["differs: " + l for l in sorted(want - have)] + ["recorded but not on disk: " + l for l in sorted(have - want)] + + +if __name__ == "__main__": + if len(sys.argv) >= 4 and sys.argv[1] == "prompt": + sys.stdout.write(read_task(sys.argv[2], sys.argv[3])["prompt"]) + elif len(sys.argv) >= 3 and sys.argv[1] == "check": + probs = check(sys.argv[2], sys.argv[3:] or None) + for p in probs: + print(p) + print("manifest OK" if not probs else "manifest MISMATCH (%d)" % len(probs)) + sys.exit(1 if probs else 0) + else: + print(__doc__) + sys.exit(2) diff --git a/scripts/e2e/codex/tasks/MANIFEST.sha256 b/scripts/e2e/codex/tasks/MANIFEST.sha256 new file mode 100644 index 00000000..8c11d2cf --- /dev/null +++ b/scripts/e2e/codex/tasks/MANIFEST.sha256 @@ -0,0 +1,203 @@ +6f413777d0e2cd1003de7c7ca802ff4d1a90b9ba96975a68e8e45407e49df2cb crm/accept.py +59b9cf609770519c12ab9bfbeb3bb1707e65b7c9f97c03a853fac79cc7c4aad2 crm/hidden/crm_acceptance.py +b453724cde02032447adb07ddec17f56dbc66dc11fefbf7129160c90fc7c7022 crm/task.md +PROMPT crm 50875f4a1552713139637db8724134768014424ff297cffa61f688397ffa8e0d +SEEDTREE crm 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b +TASK crm 4f21e987b1b80c88e10d2ab6cafeeb85df3788289d0c2698705c859b959f645d +REFERENCE crm 04f3bd297f88413c42588bde73b8bd0c8e9fe3227122ffa0ce1ff60165c85e11 +79cf9245ef49a2d152a0d46cff54ba451cbf38d78f75c5bd36598de73eccfb4a debuglog-sched/accept.py +a95e880e9c2a7e7df2f7106d43aa86e6d88eb309bb3637621bb4818bae9830b8 debuglog-sched/gen_log.py +816560cc32fecb0c4212c4526291dffc84aab0b6285103ecf1606fe66490c200 debuglog-sched/hidden/evidence.json +ffc6d8f9032bb7587a6c15736511b2b294bf6cad48447a77affe8c9c1fd717cb debuglog-sched/hidden/orig/sched/__init__.py +b2c5b733771d2bc3dd99bee690d9c602e4fbf2c3da3c8cf493e7989e3ce57714 debuglog-sched/hidden/orig/sched/clock.py +083a19f8ef4bbe2d04649ed44b3c4957d342e00ee53b1e525c4f5e5417451765 debuglog-sched/hidden/orig/sched/dedupe.py +333cf47efc624ac9dd877cdbd397c84181734b3abb212b3346e66480cd1a88d1 debuglog-sched/hidden/orig/sched/ids.py +c3d6153b0beb3be3ba69465b188a72cc4e768eca78719cf12676a7fe032501be debuglog-sched/hidden/orig/sched/lease.py +671b1c32e743cc8d78baf5c7accb65fb147abc40742d1534b7e9f8ac507ec3a8 debuglog-sched/hidden/orig/sched/logs.py +f95ce6592df16bd17e6f482b73a406ef5779347e6c308898b3de67dde915baa5 debuglog-sched/hidden/orig/sched/metrics.py +3315e3042a0e449c043c4468586fcf0d430199a054b368d215ed1a4407ee1fff debuglog-sched/hidden/orig/sched/model.py +a0e58243893026e9bd455ebe09ca4a260dd5de892d1a99b9774e9a12105edf25 debuglog-sched/hidden/orig/sched/queue.py +95756c44cc4cf8a66d0640a78a3a48a74a3ef3a40d9489cacbf16c1422ed273d debuglog-sched/hidden/orig/sched/retry.py +603e3053a0fe7a7c214b17416e3b8e735c0a15fb36487db95347e2a11b3d102e debuglog-sched/hidden/orig/sched/service.py +9b70fd4bec746d0756a989ba1d6bd6955c975e187f5bf8a656fb5956094ca9af debuglog-sched/hidden/orig/sched/sim.py +9e72b1d44e1534c5be399698248f098676dfadf75cbff7a42844a7e4137d6f1f debuglog-sched/hidden/orig/sched/store.py +16712ffc0bbb65a45aaf8af618091d5e1b796ccc71397ff5842544618a6549de debuglog-sched/hidden/orig/sched/worker.py +c102a3d6fe2592bf1bc09ddc08b62d5565304f8987e0e66a4a3ef880eac584c7 debuglog-sched/hidden/stress.py +c1843cfa16b38717bb7702dea59262ed41856a96f84a8303854389d13a876442 debuglog-sched/hidden/tests/helpers.py +5f86ecbbfd0b2bd0ae9c7b2e6e2e7d5049b1f2e0f902c063a6128a062f5703ea debuglog-sched/hidden/tests/test_ids.py +37e86a97afb6ca565757600734cd5db75ff3cc86d01bcb8a9f30d72255f7231f debuglog-sched/hidden/tests/test_lease_dedupe.py +691ed0b32061a5bff822a7816d3856f39f6bb532f927b1e35018e8149828f956 debuglog-sched/hidden/tests/test_service.py +3d6624767165d46c961f724824135f1cbb0f07588d3240301e0eb8c1eda2cca7 debuglog-sched/hidden/tests/test_sim.py +427404b7cb2a68000c9c040823ddec455d00e46a75e3df7825ceaa05dc478784 debuglog-sched/hidden/tests/test_store_queue.py +af49af474c97e5c48ed99c56f34a21ff0e4640b43c70e60749c0ea034b2809f5 debuglog-sched/seed/logs/service.log +877a32c226a527efeee6cfa49037b56c8f7cb9939e1bc3aff4cd389f0995a8de debuglog-sched/seed/run_sim.py +ffc6d8f9032bb7587a6c15736511b2b294bf6cad48447a77affe8c9c1fd717cb debuglog-sched/seed/sched/__init__.py +b2c5b733771d2bc3dd99bee690d9c602e4fbf2c3da3c8cf493e7989e3ce57714 debuglog-sched/seed/sched/clock.py +083a19f8ef4bbe2d04649ed44b3c4957d342e00ee53b1e525c4f5e5417451765 debuglog-sched/seed/sched/dedupe.py +333cf47efc624ac9dd877cdbd397c84181734b3abb212b3346e66480cd1a88d1 debuglog-sched/seed/sched/ids.py +c3d6153b0beb3be3ba69465b188a72cc4e768eca78719cf12676a7fe032501be debuglog-sched/seed/sched/lease.py +671b1c32e743cc8d78baf5c7accb65fb147abc40742d1534b7e9f8ac507ec3a8 debuglog-sched/seed/sched/logs.py +f95ce6592df16bd17e6f482b73a406ef5779347e6c308898b3de67dde915baa5 debuglog-sched/seed/sched/metrics.py +3315e3042a0e449c043c4468586fcf0d430199a054b368d215ed1a4407ee1fff debuglog-sched/seed/sched/model.py +a0e58243893026e9bd455ebe09ca4a260dd5de892d1a99b9774e9a12105edf25 debuglog-sched/seed/sched/queue.py +95756c44cc4cf8a66d0640a78a3a48a74a3ef3a40d9489cacbf16c1422ed273d debuglog-sched/seed/sched/retry.py +603e3053a0fe7a7c214b17416e3b8e735c0a15fb36487db95347e2a11b3d102e debuglog-sched/seed/sched/service.py +9b70fd4bec746d0756a989ba1d6bd6955c975e187f5bf8a656fb5956094ca9af debuglog-sched/seed/sched/sim.py +9e72b1d44e1534c5be399698248f098676dfadf75cbff7a42844a7e4137d6f1f debuglog-sched/seed/sched/store.py +16712ffc0bbb65a45aaf8af618091d5e1b796ccc71397ff5842544618a6549de debuglog-sched/seed/sched/worker.py +c1843cfa16b38717bb7702dea59262ed41856a96f84a8303854389d13a876442 debuglog-sched/seed/tests/helpers.py +5f86ecbbfd0b2bd0ae9c7b2e6e2e7d5049b1f2e0f902c063a6128a062f5703ea debuglog-sched/seed/tests/test_ids.py +37e86a97afb6ca565757600734cd5db75ff3cc86d01bcb8a9f30d72255f7231f debuglog-sched/seed/tests/test_lease_dedupe.py +691ed0b32061a5bff822a7816d3856f39f6bb532f927b1e35018e8149828f956 debuglog-sched/seed/tests/test_service.py +3d6624767165d46c961f724824135f1cbb0f07588d3240301e0eb8c1eda2cca7 debuglog-sched/seed/tests/test_sim.py +427404b7cb2a68000c9c040823ddec455d00e46a75e3df7825ceaa05dc478784 debuglog-sched/seed/tests/test_store_queue.py +e8e52f9d50662a7a1d113ccc5723b4bc4c7465668f59f00502e0f6645a523943 debuglog-sched/task.md +PROMPT debuglog-sched d596947b7043c51cd4cf36b9a35ed84a330113421d2f47d1cefb34893f507505 +SEEDTREE debuglog-sched 8ffbcf1773f488add8aa764621d4e574fcf88bf35c1c99dfbe9b75febe4d4ca3 +TASK debuglog-sched 3cd1971c02853761ebc8cd5e2ddbb89636aaf5452eccf780a0020aed01c21844 +REFERENCE debuglog-sched 0069c1f700e546bb692b14698c888742ea4dc82ae2aa3bc20f64701a5cb16026 +fa439d6b0c7e68cc66cb3cde833200cceb7c9d6cca60172680e9b172b7f41e0c feature-query/accept.py +d1f85a4c31091f1b862791927fb35929a20b95f5b64fa2ff0fb7dd8f9f370d07 feature-query/hidden/pristine_tests/test_csv_cli.py +ea62abaad8643e3d2e693983e9b543a665d5c4f940a3d270278d66a27ebee38f feature-query/hidden/pristine_tests/test_index_storage.py +2b54bed24f1e6b59ae7a3a1c46003d7b5ae194b08f55801371d41f45cbfbf702 feature-query/hidden/pristine_tests/test_schema.py +eb7d33c2e80835f87044a332ba875d2b8254b6345068a05cca5b30a817c2c9ae feature-query/hidden/pristine_tests/test_table.py +5f46ab44226bb7ecce6a36b36573876ae1a17c05995e59941df73e99587000e5 feature-query/hidden/test_hidden_spec.py +8e6a9509564adfdc4a0266b4dce93acfc455561c1b4db1e442f63ea63d740443 feature-query/seed/README.md +48028e8680af0fecf4a40034d1f61ca040376626f0025ef726638826fd0a6ef5 feature-query/seed/SPEC.md +bacc892fc5bd1fa73dff55c077841b1e23c45dbf7545def1db7767beffc22e37 feature-query/seed/minidb/__init__.py +6f8f61e59b4f1d95f2b7590c1ce4c1615cf02f09cbd494cd972e881186d4ae57 feature-query/seed/minidb/cli.py +bcd0c4cf542818fe61db4312b6f13dafb2aba118ab7118dc82dbeebaf7f4248f feature-query/seed/minidb/csvio.py +33a611456ab581e686894146e852bba53ba651982c46780ff762bf5c6b60a805 feature-query/seed/minidb/errors.py +5606d3e56a4c25fb2d4203c8d3d6b3fc547a561041e621f568a6abcccf7a850d feature-query/seed/minidb/index.py +8a5f133424959676e700158afe2c609a44985715d7d01cebce92ca7cb69aa381 feature-query/seed/minidb/schema.py +53db1e3cbe473b89ab6609784dc7d3872d3397a6582f16c613b5cd076f57dd90 feature-query/seed/minidb/storage.py +2783bf79d1ac8579fd5f9ef2566e7129d5699a603babdbce661d465593d09144 feature-query/seed/minidb/table.py +d1f85a4c31091f1b862791927fb35929a20b95f5b64fa2ff0fb7dd8f9f370d07 feature-query/seed/tests/test_csv_cli.py +ea62abaad8643e3d2e693983e9b543a665d5c4f940a3d270278d66a27ebee38f feature-query/seed/tests/test_index_storage.py +2b54bed24f1e6b59ae7a3a1c46003d7b5ae194b08f55801371d41f45cbfbf702 feature-query/seed/tests/test_schema.py +eb7d33c2e80835f87044a332ba875d2b8254b6345068a05cca5b30a817c2c9ae feature-query/seed/tests/test_table.py +f890a99921dc2a0f89f02791523a2f0d1316517612010f1bff774d502040deca feature-query/task.md +PROMPT feature-query b3c584256138f3a8315afce9beaa85271d0c2250add5a495a9787f03289cbbfd +SEEDTREE feature-query 5cf442da8591285881f72bbe06c34753924b319c55351da3da7a7b407a662440 +TASK feature-query f986b4fece91b1f7cb0722c0dcf45f9d5d3bc11591f0535dc18eb06fc3a983bc +REFERENCE feature-query fbed87863e199b1ed079caf7a00c3e0542512130bf31f4e49173c7b1e1a24958 +5c1b869972046b68422bdff0d251ad3abd393c4cdeec6c36ba2239683046c0ac fixbug-ledger/accept.py +999831ccbb0f03803cb81f6259bfbd6af98c972152c69252e051fa5a8e218cb2 fixbug-ledger/hidden/pristine_tests/helpers.py +85347be643d1edfae1cecb20eb5801d1be2038df94f579742c6482687f7c6b73 fixbug-ledger/hidden/pristine_tests/test_accounts.py +1034e8c1774082cf57af911fe50ec63c36c90ed9f1d2a4474851e5c61fed66a7 fixbug-ledger/hidden/pristine_tests/test_calendar.py +1f27195c3eca3858ad8c4c6c3f5d9f073d18ea35210bd77b8637e5bd62521e6c fixbug-ledger/hidden/pristine_tests/test_cli.py +ad44f94405a2ce4d0eb0953ce1e459d35da6e2d34181b49b7c53079a0671b495 fixbug-ledger/hidden/pristine_tests/test_exporter.py +fb320fbb0e5184cc968a60d0360a39c26a0db99220cb113743f3640f4e2925f2 fixbug-ledger/hidden/pristine_tests/test_fx.py +bd4bc42feb77648f95dc7a7829751b475ee824fda55c478237d3fc162aebc716 fixbug-ledger/hidden/pristine_tests/test_importer.py +c9a40606ecdaf27885e87645151716020a3e41f25a9ba840cb4b3ca3d42abf22 fixbug-ledger/hidden/pristine_tests/test_journal.py +113385a1dc93280bfe9c7a5b11acfbecb56519a35aee2a383a375a918569a299 fixbug-ledger/hidden/pristine_tests/test_money.py +2d7e5198a77951b4e12e9435536f03c80aa22e70309b8be6cf00470482357e87 fixbug-ledger/hidden/pristine_tests/test_reports.py +484bd8022f30ffa38a5114a924e693d5de9455dd2c22ef83d2f5aff6ce1e6859 fixbug-ledger/hidden/pristine_tests/test_rounding.py +97460a4e3ac323fdd4d36fb41f6e2bf1f809ab37faa2015615c59a64839c6e2d fixbug-ledger/hidden/pristine_tests/test_transactions.py +fbf1353ed4b7c7e7b2761287da82c34fd8e787d325278f0dcac199424c72be9d fixbug-ledger/hidden/pristine_tests/test_utils.py +6332fcbc1ad6f0feef36b7c80d47549b563d60f978de381da0ac1585150f86a6 fixbug-ledger/hidden/test_hidden.py +f405559a2ebaac0191a9b232eba29e9f8ba3785ca17e06c2b0bf7d8ce93a5ecd fixbug-ledger/seed/ledger/__init__.py +3ea21efe62ba31d237afa99c71f06fa662e3517db40085bc43a15c86d8c479aa fixbug-ledger/seed/ledger/accounts.py +248523398719790d5f063fdda022756a477edb2b44fa59e0c4c8ac181c2decdf fixbug-ledger/seed/ledger/calendar.py +110c2af6cccbd8be471b3752896248abc20346c83f8204d02642625e372dd783 fixbug-ledger/seed/ledger/cli.py +298f3b70386e08155efd4fd36f1354b9ef56275151702285bda78194eead7e46 fixbug-ledger/seed/ledger/exporter.py +6767538fa447d46749ec70d6d650e381f6de0ec4ac926673506cda708a7e5d16 fixbug-ledger/seed/ledger/fx.py +e8d215aa1898bd874044318b1c146dd8a0974de31a9a7a7fc03bb602dd197aab fixbug-ledger/seed/ledger/importer.py +72568bdefd99979e4f7119ee6bb8db32299b51543c5d4959e24496c6e9dbba07 fixbug-ledger/seed/ledger/journal.py +e14efa7a3f30957ff76512f36dcd96ab8202e59526f1d3228a6c3b808e4ba5ee fixbug-ledger/seed/ledger/money.py +a8da923eb120dc46730c697e0d3eb75dd59b9b99587bd7ae8ccd078736ca7d85 fixbug-ledger/seed/ledger/reports.py +9583515f9ad5e54db3164b0859f18e37a2f14e28e7b11940bcb86420e0ddfe00 fixbug-ledger/seed/ledger/rounding.py +bcd285a53587b9b9c64b8b5fe9974793db83eb48f0b1f7476caa83ef0e6b0945 fixbug-ledger/seed/ledger/transactions.py +18cbf5a1da40d9e50e9735535623d3c1393f23c76660d4e69ffaefabb34d4de2 fixbug-ledger/seed/ledger/utils.py +999831ccbb0f03803cb81f6259bfbd6af98c972152c69252e051fa5a8e218cb2 fixbug-ledger/seed/tests/helpers.py +85347be643d1edfae1cecb20eb5801d1be2038df94f579742c6482687f7c6b73 fixbug-ledger/seed/tests/test_accounts.py +1034e8c1774082cf57af911fe50ec63c36c90ed9f1d2a4474851e5c61fed66a7 fixbug-ledger/seed/tests/test_calendar.py +1f27195c3eca3858ad8c4c6c3f5d9f073d18ea35210bd77b8637e5bd62521e6c fixbug-ledger/seed/tests/test_cli.py +ad44f94405a2ce4d0eb0953ce1e459d35da6e2d34181b49b7c53079a0671b495 fixbug-ledger/seed/tests/test_exporter.py +fb320fbb0e5184cc968a60d0360a39c26a0db99220cb113743f3640f4e2925f2 fixbug-ledger/seed/tests/test_fx.py +bd4bc42feb77648f95dc7a7829751b475ee824fda55c478237d3fc162aebc716 fixbug-ledger/seed/tests/test_importer.py +c9a40606ecdaf27885e87645151716020a3e41f25a9ba840cb4b3ca3d42abf22 fixbug-ledger/seed/tests/test_journal.py +113385a1dc93280bfe9c7a5b11acfbecb56519a35aee2a383a375a918569a299 fixbug-ledger/seed/tests/test_money.py +2d7e5198a77951b4e12e9435536f03c80aa22e70309b8be6cf00470482357e87 fixbug-ledger/seed/tests/test_reports.py +484bd8022f30ffa38a5114a924e693d5de9455dd2c22ef83d2f5aff6ce1e6859 fixbug-ledger/seed/tests/test_rounding.py +97460a4e3ac323fdd4d36fb41f6e2bf1f809ab37faa2015615c59a64839c6e2d fixbug-ledger/seed/tests/test_transactions.py +fbf1353ed4b7c7e7b2761287da82c34fd8e787d325278f0dcac199424c72be9d fixbug-ledger/seed/tests/test_utils.py +c4f1d1d57783eda804ead793bac585c2da7ecacc1750aa209f495e32901bed7a fixbug-ledger/task.md +PROMPT fixbug-ledger 08f5c2fd63c199fa24274a7d36099354b27b7e2bde1e126a833a3a973073716b +SEEDTREE fixbug-ledger 41ba1db9dedeae30d1c189d70e45660639cb8e798bdf94dfb9a27e54bdb18c56 +TASK fixbug-ledger c6e7743467badd427a94bad605e972b9f19c78b3cd54b141501c1dee59417302 +REFERENCE fixbug-ledger 08eb07de9e7f22a9266478af9ed3643cf7bc956e32a867e903d69f2e7777f68c +2c01fffcdf4a1e959d9d3adbbd5965cf8d59e69dd330a3568966812b2f672432 refactor-shop/accept.py +f4bf75da964c784234c685b44b41c98846c6c03d46f8277115cb756d224d5f4c refactor-shop/hidden/behaviour.py +99546b78de332fc57d310eb3d0699b9d8110f662032e216c4ab886377e5588e2 refactor-shop/hidden/helpers_h.py +42fe54c2512025b108307dc77bd2da3383e18c903f546627576b8c0606692884 refactor-shop/hidden/tests/helpers.py +04834f5874086826d49418ff32b7fd25fab27c26ce033ed6af8fe9ef4df7c969 refactor-shop/hidden/tests/test_discounts.py +bdca9bbe816a81ff09edc4c74ff5d6d37b4cbc6d4f7d351e5edc77e35bcda0aa refactor-shop/hidden/tests/test_extras.py +aea1ce4cb823c6d829ef3449494a0eda439f3dc4196831c88950b787a898c1ca refactor-shop/hidden/tests/test_invoices.py +223c705dcda5eee296e136781afc2996e34d6969955d55ff9363891eaa7b2126 refactor-shop/hidden/tests/test_orders_customers.py +6754eedaee1c70fc2c209ab28dc2609589493ffc7736fb83a012213c4237a8f4 refactor-shop/hidden/tests/test_reports_cli.py +13553aa52621f19c8c9c0890f816db6b43832aa54e0936d734136716b99af08d refactor-shop/hidden/tests/test_services.py +c586c85c49c545ff2d7e343a930b4707e9f6ef100c7c86173627cf097713bed1 refactor-shop/hidden/tests/test_tax_shipping.py +7e27be2b3aae93ad60d3a586a5267470fe992c3c9dfd9eebea107092262b4da3 refactor-shop/seed/REFACTOR.md +d074cf8dc2888d831a514c242865ac4acf7adc0b6ba38a6b17fb92599bb2225a refactor-shop/seed/docs/ARCHITECTURE.md +374c39d3fa613fb5fb7de96cdcc75811d05745c474c723f553cebb021f58c0fb refactor-shop/seed/shop/__init__.py +5fb255ecdf2c9efac6cab26115724a936fc71c7eb5c776ac6a6174b4bc8f62a9 refactor-shop/seed/shop/analytics.py +e410140f39434f70d7ead874cb419173e180b002b8a68025395ddc386b373c3e refactor-shop/seed/shop/cart.py +9d58bcfe248800e1da6810e942d5c2a97a5bbb5a7264ed9a5c59e32c949d31fb refactor-shop/seed/shop/cli.py +d6273a339799bc94bcbe34892378252a8c1326ee95b17b9426553342dd167bd9 refactor-shop/seed/shop/currency.py +2b0083c86d20297265942ceed5ad29aa8845046cc229148e49f6b9200433d65a refactor-shop/seed/shop/customers.py +ecd7225da505b3f25724c861e8238193c858236a305385ebc1e2e3787bf9de50 refactor-shop/seed/shop/discounts.py +9f0d4d969b8bead49a53a0c3aaa88f9ecf6ceb97bf2fe265a1682b59bd09a211 refactor-shop/seed/shop/export.py +51adaf1b0792bf2de4156cd3a0ceb6693faae562b8d750fc66eb98860e9a709c refactor-shop/seed/shop/inventory.py +cc5c92e18cae0de9d683bd0ad2b6bf5b62343ef6094b06785ab25c7789ffc4c0 refactor-shop/seed/shop/invoices.py +189d40032fc0d6dd935f7a7c6115b4126c0241f6b45c25f76e8e27439afae11f refactor-shop/seed/shop/loyalty.py +eba38ca2d0bf635219326328d42cb9dae04ccfc00330a4936bfdb39be76dc46d refactor-shop/seed/shop/notifications.py +ceb779b89b29f7a191a1afcd988935a33ed4b34a0abdc911be1e3f7a129d865a refactor-shop/seed/shop/orders.py +3030bf82b9c200f70e65e17d955c9d8f7a7e3c3761a9f8106e4f236347d1d078 refactor-shop/seed/shop/products.py +0289e20c5744b88fd8790f1de2b77f9c09d72bb815e6aeb4697c17f5bda2935f refactor-shop/seed/shop/reports.py +226d3a79394f39fe9ddcb987538406bf1b8d37b086faa70a468fcc1e7b9b8900 refactor-shop/seed/shop/returns.py +f6112efca473e904c3af77b5759d7f57343268475054fedfdbbe159025e77ffc refactor-shop/seed/shop/sample.py +f4984646245b7996466cde4d28a26d9e4407358f33432e37459b60c902163a9c refactor-shop/seed/shop/shipping.py +7b38c2ba18b1dad2d875abd8254b8bed0467cac296c070b9f2a7336e7d1b0dc2 refactor-shop/seed/shop/storage.py +ca465f263e960368f644ea343273b3dfb47bc3f2fcd3df5af39dd4894eb7213f refactor-shop/seed/shop/tax.py +40f184a30984fef9c41f806223d43c0d3aba9096e994968d56564a0a998047aa refactor-shop/seed/shop/util.py +ed7c2bcb90e383a08451d6c0eef1f2a27ce7d06fec21510d4aec3594c58ac055 refactor-shop/seed/shop/validation.py +42fe54c2512025b108307dc77bd2da3383e18c903f546627576b8c0606692884 refactor-shop/seed/tests/helpers.py +04834f5874086826d49418ff32b7fd25fab27c26ce033ed6af8fe9ef4df7c969 refactor-shop/seed/tests/test_discounts.py +bdca9bbe816a81ff09edc4c74ff5d6d37b4cbc6d4f7d351e5edc77e35bcda0aa refactor-shop/seed/tests/test_extras.py +aea1ce4cb823c6d829ef3449494a0eda439f3dc4196831c88950b787a898c1ca refactor-shop/seed/tests/test_invoices.py +223c705dcda5eee296e136781afc2996e34d6969955d55ff9363891eaa7b2126 refactor-shop/seed/tests/test_orders_customers.py +6754eedaee1c70fc2c209ab28dc2609589493ffc7736fb83a012213c4237a8f4 refactor-shop/seed/tests/test_reports_cli.py +13553aa52621f19c8c9c0890f816db6b43832aa54e0936d734136716b99af08d refactor-shop/seed/tests/test_services.py +c586c85c49c545ff2d7e343a930b4707e9f6ef100c7c86173627cf097713bed1 refactor-shop/seed/tests/test_tax_shipping.py +0cb5c48a2d66b60c7de0f0db49310114421f3349dd034f133767e7957008d6c5 refactor-shop/task.md +PROMPT refactor-shop c5bdf450059292ab350151798b10315e2b85d44cfa7ab6ec4c22813ba7dbddb4 +SEEDTREE refactor-shop e6517cfcb2303615554e51c4ea806adb8bc31e13016ed4c0e76a6bee4b06f686 +TASK refactor-shop cb8966c83d87829ab3478355334c501f6fb52d91bc3b2dbcc1a6913ede79d5ac +REFERENCE refactor-shop 76768c5e9e356874ec4b28484cba9480f00ca2dc31ac2365efc4dc8a989a0c1a +073dce45b71fa4dea202cdbaa5c578b28d964db8ebf3f8a24747139d65860d53 smoke-mini/accept.py +2e1ee69a33c09bfe85108018756eec15f3a21edc2ac0a2e860ef88d5043de8a9 smoke-mini/hidden/pristine_tests/test_casing_stats.py +ae2f79e47cffea88b9d72f3846e833a0c0fa0afffbc2a1114f189e123c98deae smoke-mini/hidden/pristine_tests/test_words.py +367f96fb7e02c383e9956ea7e0cbed3515e61249b4008a0070afbef33826b745 smoke-mini/hidden/pristine_tests/test_wrap.py +4fcac38395af8bfc3b37eddff4e46435fa201d7116488056f131a26ff5f02459 smoke-mini/hidden/test_hidden.py +2e1ee69a33c09bfe85108018756eec15f3a21edc2ac0a2e860ef88d5043de8a9 smoke-mini/seed/tests/test_casing_stats.py +ae2f79e47cffea88b9d72f3846e833a0c0fa0afffbc2a1114f189e123c98deae smoke-mini/seed/tests/test_words.py +367f96fb7e02c383e9956ea7e0cbed3515e61249b4008a0070afbef33826b745 smoke-mini/seed/tests/test_wrap.py +bbd0aeea85b41e2435a93920cfe03daa51caa15ba2910b2978d24fae40f6952b smoke-mini/seed/textkit/__init__.py +293ef1e9a9281e5b6a14943184df43fa61c2dcc9f4774c35c61fd83c88bc2249 smoke-mini/seed/textkit/casing.py +d2e2ac08bdf24f1649444c4e44e833446dd713b8346b5940c89db11a8e7f063b smoke-mini/seed/textkit/stats.py +f7cd4b573b271cee61f7ef6bfdbdabe535bf195a3a9d7428f35016f6f991bf12 smoke-mini/seed/textkit/words.py +0614ff3004772633817a1c8726be605e574c6f3520b1b5c7cd488e740c857744 smoke-mini/seed/textkit/wrap.py +5ab0df296876874c879083a73742ec364270266e0cb3e5055b84f0824c8082a9 smoke-mini/task.md +PROMPT smoke-mini 007998d3609081db375ef8bb86238e86db2fdc2562663852f09cf133380b5866 +SEEDTREE smoke-mini 6fd0b235b5dbf4266000326071d5a2de8c71b66b1324aa2943528ce5cfe1e521 +TASK smoke-mini ec3f8b6cc156f43537cea083ddc3c37b257550f57766d7120300ab83219d68c3 +REFERENCE smoke-mini 56439ed22f5f5f29cf755bb64a7974d7fe93b963476a3a342221364cf5f59b50 +393134ef201e268df1c414f8ad337474f775a0c9f1e1bcd187ac3daa40e2e517 ttt/accept.py +995eee5321145dc74d6b379a50e5f35fb146fdf6d0faf9dc576e58bbdedbbe6a ttt/hidden/check_ttt.mjs +817e364533410c30040eb3fd9c8822d99dbd7ac2a8c79105a16a0e58451b78a0 ttt/task.md +EXTERNAL ttt three.module.min.js 08fd7545d13d2c7fb65ab691530a802dafefd638596501854f267d0fb13c39e7 691648 +PROMPT ttt 2991e6aa15ef837cf77328c0b0fd7612bac74a47b8bdccc3b7e28c7a9a8cdfaa +SEEDTREE ttt ffe51d18c45dfdc8cb62ed8ff501b7a9391f3faf83b7a2cc3b8cefe91b0d6bd1 +TASK ttt 834d7f9f074c78d13e4490ec39274b1b17553ab96839698d9c9bf077fda8101f +REFERENCE ttt 6d584d44a8c57716c4bc818193036c1315cf70ee8422665c4b3b6864d004d46f diff --git a/scripts/e2e/codex/tasks/README.md b/scripts/e2e/codex/tasks/README.md new file mode 100644 index 00000000..a30afee7 --- /dev/null +++ b/scripts/e2e/codex/tasks/README.md @@ -0,0 +1,56 @@ +# Codex task set for the lossy-vs-lossless delta study + +Task set of the study `claude/codex-lossy-delta` (runner: `scripts/e2e/codex/delta/`, plan: `docs/experiments/codex-lossy-delta.md`). +Every task is run by the real Codex CLI 0.163.0 against four stacks (vanilla Strata lossy / lossless, our port lossy / lossless). +The prompt, the seed workspace and the acceptance script are byte-identical for all four variants and are checked against `MANIFEST.sha256` +before every run (`scripts/e2e/codex/delta/verify_tasks.py`); a mismatch stops the runner. + +## Layout of one task (`tasks//`) + +```text +task.md exact prompt text between the two marker lines (see below), plus notes for the orchestrator (never sent to Codex) +seed/ the frozen seed workspace: copied byte for byte into an empty directory before every run (may be empty; files that are too + big or third-party are listed in task.md under "External seed files" with their sha256 and are copied by the runner) +accept.py objective acceptance: `python3 accept.py WORKSPACE` -> exit 0 = task done, any other exit = not done. Prints one + `PASS name` / `FAIL name :: detail` line per check. It never depends on the variant, never reads the network, finishes in < 120 s, + uses only the Python 3 standard library (must run on Python 3.9 and 3.14) and copies the workspace to a temporary directory + before running anything of it (it must not modify the workspace). +hidden/ files only the acceptance script uses (hidden tests, golden data). Never copied into the workspace. +reference/ `overlay/` = files that, copied over `seed/`, make `accept.py` pass. Used only by `selftest.py` (the acceptance must FAIL on the + bare seed and PASS on seed + overlay). Never given to Codex. +``` + +`task.md` format (the runner extracts the prompt with `delta/taskfile.py`): + +```text +--- +id: +title: +kind: +expected_rounds: - (the author's estimate of model requests; not enforced) +--- +# +(any notes for the orchestrator, free text; not sent to Codex) + +## Prompt +<!-- PROMPT BEGIN --> +the exact prompt text; Codex receives everything between the two marker lines, without the line breaks directly after BEGIN / before END +<!-- PROMPT END --> + +## External seed files +(optional) `relative/path sha256 bytes` per line +``` + +Rules for the prompt: self-contained, English, ends with an instruction to reply with a short summary when done, does not mention the study, +the variants or the acceptance script by name. The workspace is the current directory of Codex; there is no network; the machine has Python 3 +(standard library only, no pytest), `gcc` and `make`, no Rust, no Node. + +## Selftest + +`python3 scripts/e2e/codex/tasks/selftest.py [task-id ...]` checks, for each task, that the manifest matches, that `accept.py` fails on the bare seed and +passes on seed + `reference/overlay`, and that `accept.py` does not modify the workspace. Run it before `freeze.py`. + +## Freeze + +`python3 scripts/e2e/codex/tasks/freeze.py` rewrites `MANIFEST.sha256` (sha256 of every file under every task directory, plus one `TASK <id> <digest>` line +per task, plus the external files). The runner verifies the same list on the server copy (read-only, `chmod a-w`) before every cell. diff --git a/scripts/e2e/codex/tasks/crm/accept.py b/scripts/e2e/codex/tasks/crm/accept.py new file mode 100644 index 00000000..31630241 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/accept.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Acceptance for the CRM task: the REST checks of crm_acceptance.py (21 checks) run on a COPY of the workspace. + + accept.py WORKSPACE exit 0 = every check passed +""" +import os +import shutil +import subprocess +import sys +import tempfile + +ws = os.path.abspath(sys.argv[1]) +here = os.path.dirname(os.path.abspath(__file__)) +check = os.path.join(here, "hidden", "crm_acceptance.py") +tmp = tempfile.mkdtemp(prefix="crm-ws-") +try: + copy = os.path.join(tmp, "ws") + shutil.copytree(ws, copy, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.db")) + rc = subprocess.call([sys.executable, check, copy], timeout=600) +finally: + shutil.rmtree(tmp, ignore_errors=True) +sys.exit(rc) diff --git a/scripts/e2e/codex/tasks/crm/hidden/crm_acceptance.py b/scripts/e2e/codex/tasks/crm/hidden/crm_acceptance.py new file mode 100644 index 00000000..ea46f77a --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/hidden/crm_acceptance.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Acceptance script for the CRM the agent builds (offline test driver, not shipped). + + crm_acceptance.py WORKSPACE + +Starts `python3 server.py` in WORKSPACE on a free port with a fresh database, drives the REST API of prompt-crm.txt and runs +the app's own tests. Exit status 0 when every check passed. +""" +import json +import os +import socket +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +ws = os.path.abspath(sys.argv[1]) +results = [] + + +def check(name, ok, detail=""): + results.append(bool(ok)) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" :: {str(detail)[:300]}"), flush=True) + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +port = free_port() +db = os.path.join(tempfile.mkdtemp(prefix="crm-acc-"), "crm.db") +env = dict(os.environ, PORT=str(port), CRM_DB=db) +server = subprocess.Popen([sys.executable, "server.py"], cwd=ws, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +base = f"http://127.0.0.1:{port}" + + +def call(method, path, body=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(base + path, data=data, method=method, headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + raw = r.read() + try: + return r.status, (json.loads(raw) if raw else None) + except ValueError: + return r.status, raw + except urllib.error.HTTPError as e: + raw = e.read() + try: + return e.code, json.loads(raw) if raw else None + except ValueError: + return e.code, raw + + +try: + for _ in range(100): + try: + socket.create_connection(("127.0.0.1", port), timeout=0.2).close() + break + except OSError: + time.sleep(0.1) + st, _ = call("GET", "/") + check("GET / serves the front-end", st == 200, st) + st, co = call("POST", "/api/companies", {"name": "Acme Corp", "website": "https://acme.test", "industry": "tools"}) + check("create company 201 with id", st == 201 and isinstance(co, dict) and isinstance(co.get("id"), int), (st, co)) + cid = co["id"] if isinstance(co, dict) and "id" in co else 0 + st, ct = call("POST", "/api/contacts", {"name": "Wile E. Coyote", "email": "wile@acme.test", "company_id": cid}) + check("create contact 201", st == 201 and isinstance(ct, dict) and ct.get("company_id") == cid, (st, ct)) + ctid = ct.get("id") if isinstance(ct, dict) else None + st, d = call("POST", "/api/deals", {"title": "Anvil order", "amount": 1500.5, "company_id": cid, "contact_id": ctid}) + check("create deal 201 default stage lead", st == 201 and isinstance(d, dict) and d.get("stage") == "lead", (st, d)) + did = d.get("id") if isinstance(d, dict) else 0 + st, lst = call("GET", "/api/companies?q=acme") + check("search companies (case-insensitive)", st == 200 and isinstance(lst, list) and any(c.get("id") == cid for c in lst), (st, lst)) + st, lst = call("GET", "/api/contacts?q=WILE@") + check("search contacts by email", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst)) + st, d2 = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "proposal", "company_id": cid, "contact_id": ctid}) + check("update deal stage", st == 200 and isinstance(d2, dict) and d2.get("stage") == "proposal" and d2.get("amount") == 2000, (st, d2)) + st, _ = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "bogus"}) + check("invalid stage is 400", st == 400, st) + st, lst = call("GET", "/api/deals?stage=proposal&q=anvil") + check("deals filter by stage and q", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst)) + st, lst = call("GET", "/api/deals?stage=won") + check("deals filter by stage (empty)", st == 200 and lst == [], (st, lst)) + st, n = call("POST", f"/api/deals/{did}/notes", {"body": "Called, wants a quote"}) + check("add note 201", st == 201 and isinstance(n, dict) and n.get("body") == "Called, wants a quote", (st, n)) + st, ns = call("GET", f"/api/deals/{did}/notes") + check("list notes", st == 200 and isinstance(ns, list) and len(ns) == 1, (st, ns)) + st, p = call("GET", "/api/pipeline") + check("pipeline summary per stage", st == 200 and isinstance(p, dict) and set(p) == {"lead", "qualified", "proposal", "won", "lost"} + and p["proposal"]["count"] == 1 and p["proposal"]["amount"] == 2000, (st, p)) + st, _ = call("POST", "/api/companies", {"website": "x"}) + check("missing name is 400", st == 400, st) + st, _ = call("GET", "/api/deals/99999") + check("unknown id is 404", st == 404, st) + st, _ = call("DELETE", f"/api/companies/{cid}") + check("delete company 204", st == 204, st) + st, d3 = call("GET", f"/api/deals/{did}") + check("deleting the company keeps the deal and clears the reference", st == 200 and isinstance(d3, dict) and d3.get("company_id") in (None, 0), (st, d3)) + st, _ = call("DELETE", f"/api/deals/{did}") + check("delete deal 204", st == 204, st) + st, _ = call("GET", f"/api/deals/{did}") + check("deleted deal is 404", st == 404, st) +finally: + server.terminate() + try: + server.wait(10) + except subprocess.TimeoutExpired: + server.kill() + +t = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests"], cwd=ws, capture_output=True, text=True, timeout=300) +check("the app's own tests pass (unittest discover -s tests)", t.returncode == 0, t.stderr[-300:]) +check("README.md exists", os.path.exists(os.path.join(ws, "README.md"))) +print(f"SUMMARY {sum(results)}/{len(results)}") +sys.exit(0 if all(results) else 1) diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/CODE_REVIEW.md b/scripts/e2e/codex/tasks/crm/reference/overlay/CODE_REVIEW.md new file mode 100644 index 00000000..76a1191e --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/CODE_REVIEW.md @@ -0,0 +1,78 @@ +# Code review + +Phase 2 review of the whole tree. Every source and test file was read again +(`server.py`, `router.py`, `handlers.py`, `db.py`, `models.py`, `validation.py`, +`responses.py`, `errors.py`, `static/index.html` and all ten test modules). +The full list of weaknesses is below, then the three most important ones that +were fixed, with the tests that now cover them. The suite went from 125 to 137 +tests during this pass and stays green. + +## Weaknesses found + +| # | Where | Problem | Severity | Status | +|---|-------|---------|----------|--------| +| 1 | `handlers.read_body` | `Content-Length` was trusted blindly: no upper bound, negative values accepted, so one request could allocate unbounded memory | High | **Fixed** | +| 2 | `handlers.handle_one` | The catch-all answered `500 {"error": "internal server error: <exception>"}`, leaking SQL, paths and library internals to the client; `sqlite3` failures were indistinguishable from bugs | High | **Fixed** | +| 3 | `router` + `db` | A mutation and its activity entry were two separate commits, and a failed statement left an open transaction on the shared connection, so a later unrelated write could commit half a change and the log could drift from the data | High | **Fixed** | +| 4 | `validation.clean_reference` | The message used `table[:-1]`, producing "does not reference an existing companie" | Low | Fixed (caught by the new validation unit tests) | +| 5 | `db.Store.update` / `delete` | The existence check ran outside the lock, so a concurrent delete could turn a request into a 500 instead of a 404 | Medium | Fixed together with #3 | +| 6 | `db.Store._filters` | `?q=` is interpolated into a `LIKE` pattern without escaping, so `%` and `_` in a search behave as wildcards | Low | Not fixed (no injection risk, only fuzzy matching); worth an `ESCAPE` clause | +| 7 | `router.pagination` | `limit` has no upper bound, so `?limit=100000000` is allowed | Medium | Not fixed; a cap (say 1000) plus a `Retry-After`-free 400 would be the fix | +| 8 | `db` schema | The `activity` table is append-only with no retention, and there are no indexes on `deals.stage`, `notes.deal_id` or `activity.deal_id` | Medium | Not fixed; fine at this size, would matter on a long-lived server | +| 9 | `router.serve_static` | Static files are read fully into memory per request, with no `ETag`/`Last-Modified`/caching | Low | Not fixed | +| 10 | `db.Store` | One shared connection serialises every write; no WAL mode | Low | Not fixed; adequate for a single-user local tool | +| 11 | `router.handle` and `handlers.handle_one` | Both mapped exceptions to statuses independently, so a new error type had to be handled twice | Medium | Fixed as part of #2 (`responses.error_response`) | +| 12 | API semantics | `PUT` replaces every editable field, so a partial body silently clears the rest. Required by the spec, but easy to misuse from a client | Low | Documented, not changed | +| 13 | `static/index.html` | No optimistic concurrency: two tabs editing the same deal overwrite each other; `fillForm` also has a hard-to-read nested ternary | Low | Not fixed | +| 14 | `tests/test_live_server.py` | The only test that touches a real socket is skipped in sandboxes that forbid `bind()`, so end-to-end coverage is environment dependent | Medium | Accepted; the in-process harness still drives the real handler class | +| 15 | Security overall | No authentication, CSRF protection or rate limiting; the server binds to 127.0.0.1 only | n/a | Accepted for a local tool | + +## The three fixes + +### 1. Request body limits (`handlers.py`) + +`read_body` now rejects a missing-looking or negative `Content-Length` with a +400 and refuses any body larger than `handlers.MAX_BODY_BYTES` (1 MB) with a +new `PayloadTooLargeError` mapped to **413**. Notes are capped at 4000 +characters, so the limit is far above any legitimate payload. + +Covered by `tests/test_robustness.py::BodyLimitTest` (oversized body, body at +the limit, negative and non-numeric `Content-Length`). + +### 2. One error mapping, no internal leakage (`responses.py`, `router.py`, `handlers.py`) + +`responses.error_response(exc)` is now the single place that turns an +application error into a status (400 validation, 409 conflict, 413 payload, +404 not found, 405 method), and both the router and the HTTP adapter use it. +Anything unexpected is logged with a full traceback on the server side and +answered with the fixed body `{"error": "internal server error"}`; +`sqlite3.IntegrityError` becomes **409** "the change conflicts with existing +data" instead of a 500. A dropped client connection (`BrokenPipeError`, +`ConnectionResetError`) no longer triggers a second send attempt. + +Covered by `tests/test_robustness.py::ErrorMappingTest`, which asserts that a +forced `sqlite3.OperationalError` produces a 500 whose body does not contain +the failing SQL text. + +### 3. Atomic mutations and transaction hygiene (`db.py`, `router.py`) + +`Store.transaction()` is a context manager that holds the lock, commits on +success and rolls back on any exception. `create`, `update`, `delete` and +`add_note` each take a `log_action` argument and write their activity row +inside that same transaction, so a record and its log entry can never drift +apart. The existence checks moved inside the lock, which also removes the +check-then-act race that used to turn a concurrent delete into a 500. The +router no longer writes to the log separately. + +Covered by `tests/test_robustness.py::AtomicActivityTest`: exactly one entry +per successful mutation, none for a rejected request, a foreign key violation +leaves both the row and the log untouched, and no transaction is left open +after a failure. + +## Deliberately left alone + +Items 6 to 15 above are recorded rather than fixed: they are either mandated +by the specification (`PUT` semantics), acceptable for a loopback-only local +tool (no auth, one connection), or performance work that needs a real workload +to justify. Item 4 was a genuine bug and was fixed as a side effect of the +validation unit tests. diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/README.md b/scripts/e2e/codex/tasks/crm/reference/overlay/README.md new file mode 100644 index 00000000..1dda4151 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/README.md @@ -0,0 +1,144 @@ +# Mini CRM + +A small CRM web application written with the Python 3 standard library only +(`http.server`, `sqlite3`, `json`, `unittest`, `urllib`). No third-party +packages, no network access required. + +## Run + +```sh +python3 server.py # http://127.0.0.1:8000 +PORT=8080 CRM_DB=crm.db python3 server.py +``` + +| Variable | Default | Meaning | +|----------|------------|-------------------------------| +| `PORT` | `8000` | TCP port, always on 127.0.0.1 | +| `CRM_DB` | `crm.db` | SQLite database file | + +Tables are created on first start. The single page app is served at `GET /`. + +## Test + +```sh +python3 -m unittest discover -s tests +``` + +The suite runs offline. Most tests drive the real request handler in process; +`tests/test_live_server.py` additionally starts a listening server and is +skipped automatically when the environment forbids opening a socket. + +## Data model + +| Table | Columns | +|-----------|----------------------------------------------------------------| +| companies | `id`, `name` (required), `website`, `industry` | +| contacts | `id`, `name` (required), `email`, `phone`, `company_id` → companies | +| deals | `id`, `title` (required), `amount` (number ≥ 0, default 0), `stage` (default `lead`), `company_id` → companies, `contact_id` → contacts, `created_at` | +| notes | `id`, `deal_id` → deals, `body` (required), `created_at` | +| activity | `id`, `created_at`, `action` (create/update/delete), `entity`, `entity_id`, `deal_id`, `summary` | + +Every create, update and delete appends one `activity` row in the same SQLite +transaction as the change itself, so the log can never drift from the data. + +Deal stages are exactly `lead`, `qualified`, `proposal`, `won`, `lost`. +Foreign keys use `ON DELETE SET NULL`, so deleting a company or contact keeps +the deals and only clears the reference; deleting a deal removes its notes. + +## API + +All bodies and responses are JSON (`Content-Type: application/json`). +Unknown ids answer `404 {"error": "..."}`, invalid input answers +`400 {"error": "..."}`, and a known route used with the wrong verb answers +`405 {"error": "..."}`. An oversized body answers `413 {"error": "..."}` and a +database conflict answers `409 {"error": "..."}`; unexpected failures return a +generic `500` and are logged with a traceback on the server side. + +For each resource `companies`, `contacts`, `deals`: + +| Method & path | Behaviour | +|-------------------|----------------------------------------------------------| +| `GET /api/<r>` | list all; `?q=text` case-insensitive substring match on name/title/email, deals also accept `?stage=<stage>` | +| `POST /api/<r>` | create, `201` + the record including its integer `id` | +| `GET /api/<r>/{id}` | fetch one record | +| `PUT /api/<r>/{id}` | replace the editable fields, `200` + the record | +| `DELETE /api/<r>/{id}` | delete, `204` with no body | + +Every list endpoint also accepts `?limit=N&offset=M` (no limit and `offset=0` +by default) and always answers with an `X-Total-Count` header holding the +number of records matching the filters, ignoring the page. + +Notes: + +| Method & path | Behaviour | +|----------------------------|-------------------------------------------------------| +| `GET /api/deals/{id}/notes` | list the notes of a deal, oldest first | +| `POST /api/deals/{id}/notes` | create a note, body `{"body": "text"}` is required | + +Pipeline: + +| Method & path | Behaviour | +|-------------------|----------------------------------------------------------------------| +| `GET /api/pipeline` | `{"lead": {"count": n, "amount": total}, ...}` for every stage | + +CSV export (same `q`, `stage`, `limit` and `offset` parameters, header row, +RFC 4180 quoting, `Content-Disposition: attachment`): + +| Method & path | Behaviour | +|----------------------------|---------------------------------------------| +| `GET /api/companies.csv` | companies as `text/csv` | +| `GET /api/contacts.csv` | contacts as `text/csv` | +| `GET /api/deals.csv` | deals as `text/csv` | + +Activity log: + +| Method & path | Behaviour | +|----------------------|-----------------------------------------------------------------------| +| `GET /api/activity` | newest entries first; `?limit=N`, `?offset=M`, `?entity=<r>`, `?deal_id=<id>`, plus `X-Total-Count` | + +### Examples + +```sh +curl -s -X POST localhost:8000/api/companies \ + -H 'Content-Type: application/json' \ + -d '{"name":"Acme","industry":"tools"}' + +curl -s -X POST localhost:8000/api/deals \ + -H 'Content-Type: application/json' \ + -d '{"title":"Rollout","amount":4200,"stage":"qualified","company_id":1}' + +curl -s 'localhost:8000/api/deals?stage=qualified&q=roll' +curl -s -X POST localhost:8000/api/deals/1/notes -d '{"body":"kickoff call booked"}' +curl -s localhost:8000/api/pipeline +curl -s -D - -o /dev/null 'localhost:8000/api/companies?limit=2' # X-Total-Count +curl -s localhost:8000/api/deals.csv +curl -s 'localhost:8000/api/activity?deal_id=1&limit=5' +``` + +## Front-end + +`static/index.html` is a dependency free single page app: companies list, +contacts list, a deals board with one column per stage, a search box that +filters every list through the API, create/edit/delete forms for the three +resources, and a deal detail panel showing the notes (with an add-note form) +and the activity of that deal. Keyboard shortcuts: `/` focuses the search box, +`Esc` closes the deal panel. + +## Layout + +``` +server.py entry point: env config, server class, re-exports +router.py routes → responses, pagination, CSV, static files +handlers.py http.server adapter (bytes in, bytes out) +db.py SQLite schema and access, atomic activity logging +models.py resource registry, stages, validators per resource +validation.py shared input validation helpers +responses.py Response/FileResponse and the error → status mapping +errors.py the exception types behind 400/404/405/413 +static/index.html single page front-end +tests/ unittest suite (one module per area of the API) +CODE_REVIEW.md phase 2 review: weaknesses found and the fixes applied +``` + +`python3 server.py` is still the only entry point; the modules above are +imported by it and `import server` still exposes them. diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/db.py b/scripts/e2e/codex/tasks/crm/reference/overlay/db.py new file mode 100644 index 00000000..e42e38d8 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/db.py @@ -0,0 +1,264 @@ +"""SQLite access layer.""" + +import os +import sqlite3 +import threading +from contextlib import contextmanager + +from errors import NotFoundError +from models import RESOURCES, STAGES, now_iso, record_label + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS companies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + website TEXT NOT NULL DEFAULT '', + industry TEXT NOT NULL DEFAULT '' +); +CREATE TABLE IF NOT EXISTS contacts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + email TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL +); +CREATE TABLE IF NOT EXISTS deals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + amount REAL NOT NULL DEFAULT 0, + stage TEXT NOT NULL DEFAULT 'lead', + company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL, + contact_id INTEGER REFERENCES contacts(id) ON DELETE SET NULL, + created_at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS notes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE, + body TEXT NOT NULL, + created_at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS activity ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + action TEXT NOT NULL, + entity TEXT NOT NULL, + entity_id INTEGER NOT NULL, + deal_id INTEGER, + summary TEXT NOT NULL +); +""" + + +def _paging(sql, params, limit, offset): + """Append a SQLite page clause; OFFSET alone needs ``LIMIT -1``.""" + page_params = list(params) + if limit is not None: + sql += " LIMIT ? OFFSET ?" + page_params.extend([limit, offset]) + elif offset: + sql += " LIMIT -1 OFFSET ?" + page_params.append(offset) + return sql, page_params + + +def activity_params(action, entity, record): + """Build the activity row for a mutation, linked to its deal when known.""" + if entity == "notes": + deal_id = record.get("deal_id") + elif entity == "deals": + deal_id = record["id"] + else: + deal_id = None + return (now_iso(), action, entity, record["id"], deal_id, record_label(entity, record)) + + +class Store: + """One SQLite connection guarded by a lock (the server is threaded).""" + + def __init__(self, path): + self.path = path + self.lock = threading.RLock() + directory = os.path.dirname(os.path.abspath(path)) + if directory and not os.path.isdir(directory): + os.makedirs(directory, exist_ok=True) + self.conn = sqlite3.connect(path, check_same_thread=False) + self.conn.row_factory = sqlite3.Row + with self.lock: + self.conn.execute("PRAGMA foreign_keys = ON") + self.conn.executescript(SCHEMA) + self.conn.commit() + + def close(self): + with self.lock: + self.conn.close() + + @contextmanager + def transaction(self): + """Hold the lock and commit on success, roll back on any failure.""" + with self.lock: + try: + yield + self.conn.commit() + except BaseException: + self.conn.rollback() + raise + + def exists(self, table, record_id): + with self.lock: + row = self.conn.execute( + "SELECT 1 FROM %s WHERE id = ?" % table, (record_id,) + ).fetchone() + return row is not None + + def _filters(self, resource, q=None, stage=None): + cfg = RESOURCES[resource] + where, params = [], [] + if q: + clauses = ["LOWER(%s) LIKE LOWER(?)" % field for field in cfg["search"]] + where.append("(%s)" % " OR ".join(clauses)) + params.extend(["%%%s%%" % q] * len(clauses)) + if stage and resource == "deals": + where.append("stage = ?") + params.append(stage) + return where, params + + def list(self, resource, q=None, stage=None, limit=None, offset=0): + cfg = RESOURCES[resource] + where, params = self._filters(resource, q, stage) + sql = "SELECT * FROM %s" % cfg["table"] + if where: + sql += " WHERE " + " AND ".join(where) + sql += " ORDER BY id" + sql, page_params = _paging(sql, params, limit, offset) + with self.lock: + rows = self.conn.execute(sql, page_params).fetchall() + total = self.conn.execute( + "SELECT COUNT(*) FROM %s%s" + % (cfg["table"], (" WHERE " + " AND ".join(where)) if where else ""), + params, + ).fetchone()[0] + return [dict(row) for row in rows], int(total) + + def get(self, resource, record_id): + cfg = RESOURCES[resource] + with self.lock: + row = self.conn.execute( + "SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,) + ).fetchone() + if row is None: + raise NotFoundError("%s %s not found" % (resource, record_id)) + return dict(row) + + def create(self, resource, values, log_action=None): + cfg = RESOURCES[resource] + columns = list(values.keys()) + sql = "INSERT INTO %s (%s) VALUES (%s)" % ( + cfg["table"], + ", ".join(columns), + ", ".join("?" for _ in columns), + ) + with self.transaction(): + cursor = self.conn.execute(sql, [values[c] for c in columns]) + record_id = cursor.lastrowid + if log_action: + created = self.conn.execute( + "SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,) + ).fetchone() + self._append_activity(activity_params(log_action, resource, dict(created))) + return self.get(resource, record_id) + + def update(self, resource, record_id, values, log_action=None): + cfg = RESOURCES[resource] + columns = list(values.keys()) + sql = "UPDATE %s SET %s WHERE id = ?" % ( + cfg["table"], + ", ".join("%s = ?" % column for column in columns), + ) + with self.transaction(): + self.get(resource, record_id) + self.conn.execute(sql, [values[c] for c in columns] + [record_id]) + updated = self.conn.execute( + "SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,) + ).fetchone() + if updated is None: + raise NotFoundError("%s %s not found" % (resource, record_id)) + if log_action: + self._append_activity(activity_params(log_action, resource, dict(updated))) + return self.get(resource, record_id) + + def delete(self, resource, record_id, log_action=None): + cfg = RESOURCES[resource] + with self.transaction(): + record = self.get(resource, record_id) + self.conn.execute("DELETE FROM %s WHERE id = ?" % cfg["table"], (record_id,)) + if log_action: + self._append_activity(activity_params(log_action, resource, record)) + return record + + def _append_activity(self, params): + """Insert one activity row inside the caller's transaction.""" + self.conn.execute( + "INSERT INTO activity (created_at, action, entity, entity_id, deal_id, summary)" + " VALUES (?, ?, ?, ?, ?, ?)", + params, + ) + + def list_activity(self, limit=None, offset=0, deal_id=None, entity=None): + where, params = [], [] + if deal_id is not None: + where.append("deal_id = ?") + params.append(deal_id) + if entity: + where.append("entity = ?") + params.append(entity) + sql = "SELECT * FROM activity" + if where: + sql += " WHERE " + " AND ".join(where) + count_sql = sql.replace("SELECT *", "SELECT COUNT(*)") + sql += " ORDER BY id DESC" + sql, page_params = _paging(sql, params, limit, offset) + with self.lock: + rows = self.conn.execute(sql, page_params).fetchall() + total = self.conn.execute(count_sql, params).fetchone()[0] + return [dict(row) for row in rows], int(total) + + def list_notes(self, deal_id, limit=None, offset=0): + self.get("deals", deal_id) + sql, page_params = _paging( + "SELECT * FROM notes WHERE deal_id = ? ORDER BY id", [deal_id], limit, offset + ) + with self.lock: + rows = self.conn.execute( + sql, page_params + ).fetchall() + total = self.conn.execute( + "SELECT COUNT(*) FROM notes WHERE deal_id = ?", (deal_id,) + ).fetchone()[0] + return [dict(row) for row in rows], int(total) + + def add_note(self, deal_id, body, log_action=None): + self.get("deals", deal_id) + with self.transaction(): + cursor = self.conn.execute( + "INSERT INTO notes (deal_id, body, created_at) VALUES (?, ?, ?)", + (deal_id, body, now_iso()), + ) + if log_action: + created = self.conn.execute( + "SELECT * FROM notes WHERE id = ?", (cursor.lastrowid,) + ).fetchone() + self._append_activity(activity_params(log_action, "notes", dict(created))) + row = self.conn.execute("SELECT * FROM notes WHERE id = ?", (cursor.lastrowid,)).fetchone() + return dict(row) + + def pipeline(self): + with self.lock: + rows = self.conn.execute( + "SELECT stage, COUNT(*) AS count, COALESCE(SUM(amount), 0) AS amount" + " FROM deals GROUP BY stage" + ).fetchall() + totals = {stage: {"count": 0, "amount": 0.0} for stage in STAGES} + for row in rows: + if row["stage"] in totals: + totals[row["stage"]] = {"count": int(row["count"]), "amount": float(row["amount"])} + return totals diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/errors.py b/scripts/e2e/codex/tasks/crm/reference/overlay/errors.py new file mode 100644 index 00000000..95520c8c --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/errors.py @@ -0,0 +1,21 @@ +"""Exceptions shared by the CRM layers; each maps to an HTTP status.""" + + +class ValidationError(ValueError): + """Raised when client input cannot be accepted (HTTP 400).""" + + +class NotFoundError(Exception): + """Raised when a record or route does not exist (HTTP 404).""" + + +class MethodNotAllowedError(Exception): + """Raised when a route exists but not for this method (HTTP 405).""" + + def __init__(self, allowed=()): + super().__init__("method not allowed") + self.allowed = tuple(allowed) + + +class PayloadTooLargeError(Exception): + """Raised when a request body exceeds the accepted size (HTTP 413).""" diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/handlers.py b/scripts/e2e/codex/tasks/crm/reference/overlay/handlers.py new file mode 100644 index 00000000..17a4c94e --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/handlers.py @@ -0,0 +1,99 @@ +"""The http.server adapter: bytes in, bytes out.""" + +import json +import os +import sqlite3 +import traceback +from http.server import BaseHTTPRequestHandler + +from errors import PayloadTooLargeError, ValidationError +from responses import Response, error_response + +MAX_BODY_BYTES = 1_000_000 + + +class CRMRequestHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + server_version = "MiniCRM/1.0" + + @property + def app(self): + return self.server.app + + def log_message(self, fmt, *args): + if os.environ.get("CRM_VERBOSE"): + super().log_message(fmt, *args) + + def read_body(self): + raw_length = self.headers.get("Content-Length") + try: + length = int(raw_length or 0) + except ValueError: + raise ValidationError("Content-Length must be a number") + if length < 0: + raise ValidationError("Content-Length must be a number") + if length > MAX_BODY_BYTES: + raise PayloadTooLargeError( + "request body is larger than %d bytes" % MAX_BODY_BYTES + ) + raw = self.rfile.read(length) if length > 0 else b"" + if not raw: + return None + try: + return json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + raise ValidationError("request body must be valid JSON") + + def process(self, method): + body = self.read_body() if method in ("POST", "PUT", "PATCH") else None + return self.app.handle(method, self.path, body) + + def send(self, response): + self.send_response(response.status) + if response.content_type: + self.send_header("Content-Type", response.content_type) + self.send_header("Content-Length", str(len(response.body))) + for key, value in response.headers.items(): + self.send_header(key, value) + self.end_headers() + if response.body and self.command != "HEAD": + self.wfile.write(response.body) + + def handle_one(self, method): + try: + response = self.process(method) + except (BrokenPipeError, ConnectionResetError): + return # the client hung up; there is nobody left to answer + except Exception as exc: + response = error_response(exc) + if response is None: + response = self.unexpected_error(exc) + try: + self.send(response) + except (BrokenPipeError, ConnectionResetError): + pass + + def unexpected_error(self, exc): + """Log the failure server side, answer with a generic message.""" + traceback.print_exc() + if isinstance(exc, sqlite3.IntegrityError): + return Response(409, {"error": "the change conflicts with existing data"}) + return Response(500, {"error": "internal server error"}) + + def do_GET(self): + self.handle_one("GET") + + def do_HEAD(self): + self.handle_one("HEAD") + + def do_POST(self): + self.handle_one("POST") + + def do_PUT(self): + self.handle_one("PUT") + + def do_DELETE(self): + self.handle_one("DELETE") + + def do_PATCH(self): + self.handle_one("PATCH") diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/models.py b/scripts/e2e/codex/tasks/crm/reference/overlay/models.py new file mode 100644 index 00000000..f7275faa --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/models.py @@ -0,0 +1,95 @@ +"""Resource definitions: stages, editable fields, validators and labels.""" + +from datetime import datetime, timezone + +from validation import ( + clean_amount, + clean_email, + clean_reference, + clean_stage, + clean_text, +) + +STAGES = ("lead", "qualified", "proposal", "won", "lost") +DEFAULT_STAGE = "lead" + + +def now_iso(): + """Timestamp used by the records and by the activity log.""" + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def validate_company(store, data): + return { + "name": clean_text(data.get("name"), "name", required=True), + "website": clean_text(data.get("website"), "website"), + "industry": clean_text(data.get("industry"), "industry"), + } + + +def validate_contact(store, data): + return { + "name": clean_text(data.get("name"), "name", required=True), + "email": clean_email(data.get("email"), "email"), + "phone": clean_text(data.get("phone"), "phone"), + "company_id": clean_reference(store, data.get("company_id"), "companies", "company_id", "company"), + } + + +def validate_deal(store, data): + return { + "title": clean_text(data.get("title"), "title", required=True), + "amount": clean_amount(data.get("amount"), "amount"), + "stage": clean_stage(data.get("stage"), STAGES, "stage", DEFAULT_STAGE), + "company_id": clean_reference(store, data.get("company_id"), "companies", "company_id", "company"), + "contact_id": clean_reference(store, data.get("contact_id"), "contacts", "contact_id", "contact"), + } + + +RESOURCES = { + "companies": { + "table": "companies", + "singular": "company", + "search": ("name",), + "fields": ("name", "website", "industry"), + "validate": validate_company, + "label": "name", + "csv_columns": ("id", "name", "website", "industry"), + }, + "contacts": { + "table": "contacts", + "singular": "contact", + "search": ("name", "email"), + "fields": ("name", "email", "phone", "company_id"), + "validate": validate_contact, + "label": "name", + "csv_columns": ("id", "name", "email", "phone", "company_id"), + }, + "deals": { + "table": "deals", + "singular": "deal", + "search": ("title",), + "fields": ("title", "amount", "stage", "company_id", "contact_id"), + "validate": validate_deal, + "auto": {"created_at": now_iso}, + "label": "title", + "csv_columns": ("id", "title", "amount", "stage", "company_id", "contact_id", "created_at"), + }, +} + + +def record_label(resource, record): + """Short human readable description used in the activity log.""" + if resource == "notes": + return note_label(record) + field = RESOURCES[resource]["label"] + label = (record.get(field) or "").strip() or "#%s" % record.get("id") + return '%s "%s"' % (RESOURCES[resource]["singular"], label) + + +def note_label(note): + """Short description of a note, truncated to keep the log readable.""" + body = " ".join((note.get("body") or "").split()) + if len(body) > 80: + body = body[:79] + "…" + return 'note "%s"' % body diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/responses.py b/scripts/e2e/codex/tasks/crm/reference/overlay/responses.py new file mode 100644 index 00000000..cb113002 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/responses.py @@ -0,0 +1,60 @@ +"""Response objects returned by the router.""" + +import json + +from errors import ( + MethodNotAllowedError, + NotFoundError, + PayloadTooLargeError, + ValidationError, +) + +CONTENT_TYPES = { + ".html": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".js": "application/javascript; charset=utf-8", + ".json": "application/json", + ".csv": "text/csv; charset=utf-8", + ".svg": "image/svg+xml", + ".png": "image/png", + ".ico": "image/x-icon", +} + + +class Response: + """A JSON (or empty) HTTP response.""" + + def __init__(self, status, payload=None, headers=None): + self.status = status + self.payload = payload + self.headers = dict(headers or {}) + if payload is None: + self.body = b"" + self.content_type = None + else: + self.body = json.dumps(payload).encode("utf-8") + self.content_type = "application/json" + + +class FileResponse(Response): + """A response with a pre-rendered body and an explicit content type.""" + + def __init__(self, status, body, content_type, headers=None): + self.status = status + self.payload = None + self.headers = dict(headers or {}) + self.body = body + self.content_type = content_type + + +def error_response(exc): + """Map a known application error to a response, or None if it is unexpected.""" + if isinstance(exc, ValidationError): + return Response(400, {"error": str(exc)}) + if isinstance(exc, PayloadTooLargeError): + return Response(413, {"error": str(exc)}) + if isinstance(exc, NotFoundError): + return Response(404, {"error": str(exc)}) + if isinstance(exc, MethodNotAllowedError): + return Response(405, {"error": str(exc)}, {"Allow": ", ".join(exc.allowed)}) + return None diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/router.py b/scripts/e2e/codex/tasks/crm/reference/overlay/router.py new file mode 100644 index 00000000..1a74b822 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/router.py @@ -0,0 +1,176 @@ +"""Request routing: turns (method, path, body) into a Response.""" + +import csv +import io +import os +from urllib.parse import parse_qs, unquote, urlparse + +from errors import MethodNotAllowedError, NotFoundError, ValidationError +from models import RESOURCES +from responses import CONTENT_TYPES, FileResponse, Response, error_response +from validation import ( + MAX_NOTE_LEN, + clean_text, + parse_id, + parse_int_param, + require_object, +) + + +def pagination(query): + """Extract limit/offset from a query string (limit absent means "all").""" + limit = parse_int_param(query["limit"], "limit", 0) if query.get("limit") is not None else None + offset = parse_int_param(query.get("offset", "0"), "offset", 0) + return limit, offset + + +def render_csv(resource, records): + """Render records as CSV with a header row and RFC 4180 quoting.""" + columns = RESOURCES[resource]["csv_columns"] + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\r\n") + writer.writerow(columns) + for record in records: + writer.writerow(["" if record.get(column) is None else record.get(column) for column in columns]) + return buffer.getvalue().encode("utf-8") + + +class CRMApp: + """Transport agnostic dispatcher: everything except the socket.""" + + def __init__(self, store, static_dir): + self.store = store + self.static_dir = static_dir + + def handle(self, method, raw_path, body=None): + method = method.upper() + parsed = urlparse(raw_path) + path = unquote(parsed.path) or "/" + query = {} + for key, values in parse_qs(parsed.query, keep_blank_values=True).items(): + query[key] = values[-1] + try: + if path.startswith("/api/"): + return self.handle_api(method, path, query, body) + return self.serve_static(method, path) + except (ValidationError, NotFoundError, MethodNotAllowedError) as exc: + return error_response(exc) + + def serve_static(self, method, path): + if method not in ("GET", "HEAD"): + raise MethodNotAllowedError(("GET", "HEAD")) + if path in ("/", "/index.html"): + relative = "index.html" + elif path.startswith("/static/"): + relative = path[len("/static/"):] + else: + raise NotFoundError("%s not found" % path) + root = os.path.realpath(self.static_dir) + target = os.path.realpath(os.path.join(root, relative)) + if target != root and not target.startswith(root + os.sep): + raise NotFoundError("%s not found" % path) + if not os.path.isfile(target): + raise NotFoundError("%s not found" % path) + with open(target, "rb") as handle: + content = handle.read() + content_type = CONTENT_TYPES.get(os.path.splitext(target)[1].lower(), "application/octet-stream") + return FileResponse(200, content, content_type) + + def handle_api(self, method, path, query, body): + parts = [part for part in path.split("/") if part] + if parts == ["api", "pipeline"]: + if method != "GET": + raise MethodNotAllowedError(("GET",)) + return Response(200, self.store.pipeline()) + if parts == ["api", "activity"]: + return self.activity(method, query) + if len(parts) == 2 and parts[1].endswith(".csv"): + return self.export_csv(method, parts[1][: -len(".csv")], query) + if len(parts) >= 2 and parts[1] in RESOURCES: + resource = parts[1] + if len(parts) == 2: + return self.collection(method, resource, query, body) + if len(parts) == 3: + return self.record(method, resource, parts[2], body) + if len(parts) == 4 and parts[1] == "deals" and parts[3] == "notes": + return self.notes(method, parts[2], body, query) + raise NotFoundError("%s not found" % path) + + def activity(self, method, query): + if method != "GET": + raise MethodNotAllowedError(("GET",)) + limit, offset = pagination(query) + deal_id = None + if query.get("deal_id"): + deal_id = parse_int_param(query["deal_id"], "deal_id", 1) + entries, total = self.store.list_activity( + limit=limit, offset=offset, deal_id=deal_id, entity=query.get("entity") or None + ) + return Response(200, entries, {"X-Total-Count": str(total)}) + + def export_csv(self, method, resource, query): + if resource not in RESOURCES: + raise NotFoundError("/api/%s.csv not found" % resource) + if method not in ("GET", "HEAD"): + raise MethodNotAllowedError(("GET", "HEAD")) + limit, offset = pagination(query) + records, _total = self.store.list( + resource, + q=query.get("q") or None, + stage=query.get("stage") or None, + limit=limit, + offset=offset, + ) + filename = "%s.csv" % resource + return FileResponse( + 200, + render_csv(resource, records), + CONTENT_TYPES[".csv"], + {"Content-Disposition": 'attachment; filename="%s"' % filename}, + ) + + def collection(self, method, resource, query, body): + if method == "GET": + limit, offset = pagination(query) + records, total = self.store.list( + resource, + q=query.get("q") or None, + stage=query.get("stage") or None, + limit=limit, + offset=offset, + ) + return Response(200, records, {"X-Total-Count": str(total)}) + if method == "POST": + values = RESOURCES[resource]["validate"](self.store, require_object(body)) + for column, factory in RESOURCES[resource].get("auto", {}).items(): + values[column] = factory() + record = self.store.create(resource, values, log_action="create") + return Response(201, record) + raise MethodNotAllowedError(("GET", "POST")) + + def record(self, method, resource, raw_id, body): + record_id = parse_id(raw_id) + if method == "GET": + return Response(200, self.store.get(resource, record_id)) + if method == "PUT": + values = RESOURCES[resource]["validate"](self.store, require_object(body)) + record = self.store.update(resource, record_id, values, log_action="update") + return Response(200, record) + if method == "DELETE": + record = self.store.delete(resource, record_id, log_action="delete") + return Response(204) + raise MethodNotAllowedError(("GET", "PUT", "DELETE")) + + def notes(self, method, raw_id, body, query=None): + deal_id = parse_id(raw_id) + if method == "GET": + limit, offset = pagination(query) + notes, total = self.store.list_notes(deal_id, limit=limit, offset=offset) + return Response(200, notes, {"X-Total-Count": str(total)}) + if method == "POST": + text = clean_text( + require_object(body).get("body"), "body", required=True, max_len=MAX_NOTE_LEN + ) + note = self.store.add_note(deal_id, text, log_action="create") + return Response(201, note) + raise MethodNotAllowedError(("GET", "POST")) diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/server.py b/scripts/e2e/codex/tasks/crm/reference/overlay/server.py new file mode 100644 index 00000000..15aa9ce6 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/server.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Entry point of the Mini CRM. + +Run it with ``python3 server.py``. Configuration comes from the environment: + +* ``PORT`` -- TCP port, default 8000 (always bound to 127.0.0.1) +* ``CRM_DB`` -- SQLite file, default ``crm.db`` + +The implementation lives in the sibling modules ``db``, ``models``, +``validation``, ``responses``, ``router`` and ``handlers``. This module wires +them together and re-exports their public names, so ``import server`` keeps +working for the tests and for scripts built on top of it. +""" + +import os +from http.server import ThreadingHTTPServer + +from db import SCHEMA, Store +from errors import MethodNotAllowedError, NotFoundError, ValidationError +from handlers import CRMRequestHandler +from models import DEFAULT_STAGE, RESOURCES, STAGES, now_iso +from responses import CONTENT_TYPES, FileResponse, Response +from router import CRMApp +from validation import ( + EMAIL_RE, + MAX_NOTE_LEN, + MAX_TEXT_LEN, + clean_amount, + clean_email, + clean_reference, + clean_stage, + clean_text, + parse_id, + require_object, +) + +HOST = "127.0.0.1" +DEFAULT_PORT = 8000 +DEFAULT_DB = "crm.db" +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +STATIC_DIR = os.path.join(BASE_DIR, "static") + +__all__ = [ + "CONTENT_TYPES", "CRMApp", "CRMRequestHandler", "CRMServer", "DEFAULT_DB", + "DEFAULT_PORT", "DEFAULT_STAGE", "EMAIL_RE", "FileResponse", "HOST", + "MAX_NOTE_LEN", "MAX_TEXT_LEN", "MethodNotAllowedError", "NotFoundError", + "RESOURCES", "Response", "SCHEMA", "STAGES", "STATIC_DIR", "Store", + "ValidationError", "clean_amount", "clean_email", "clean_reference", + "clean_stage", "clean_text", "config_from_env", "create_server", "main", + "now_iso", "parse_id", "require_object", +] + + +class CRMServer(ThreadingHTTPServer): + """Binds the CRM app to a loopback TCP port.""" + + allow_reuse_address = True + daemon_threads = True + + def __init__(self, host, port, db_path, static_dir=STATIC_DIR): + self.app = CRMApp(Store(db_path), static_dir) + super().__init__((host, port), CRMRequestHandler) + + def shutdown(self): + super().shutdown() + self.app.store.close() + + +def create_server(port=None, db_path=None, host=HOST): + return CRMServer(host, int(port), db_path) + + +def config_from_env(environ=None): + """Read PORT and CRM_DB, with the documented defaults.""" + environ = os.environ if environ is None else environ + raw_port = environ.get("PORT", str(DEFAULT_PORT)) + try: + port = int(raw_port) + except ValueError: + raise SystemExit("PORT must be an integer, got %r" % raw_port) + return port, environ.get("CRM_DB", DEFAULT_DB) + + +def main(argv=None): + port, db_path = config_from_env() + server = create_server(port, db_path) + print( + "CRM listening on http://%s:%d (db: %s)" + % (server.server_address[0], server.server_address[1], db_path) + ) + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nshutting down") + finally: + server.shutdown() + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/static/index.html b/scripts/e2e/codex/tasks/crm/reference/overlay/static/index.html new file mode 100644 index 00000000..1fa66b32 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/static/index.html @@ -0,0 +1,414 @@ +<!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<title>Mini CRM + + + +
+

Mini CRM

+ + +
+
+
+

Companies

+
+ + + + + +
+
    +
    + +
    +

    Contacts

    +
    + + + + + + +
    +
      +
      + +
      +

      Deals

      +
      + + + + + + + +
      +
      +
      + + +
      + + + + diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/__init__.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/__init__.py new file mode 100644 index 00000000..4a442705 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/__init__.py @@ -0,0 +1 @@ +"""Test package for the CRM application.""" diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/base.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/base.py new file mode 100644 index 00000000..6ea7a68c --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/base.py @@ -0,0 +1,156 @@ +"""Shared helpers: drive the real HTTP handler without opening a socket.""" + +import io +import json +import os +import shutil +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +import server as server_module # noqa: E402 + + +class FakeSocket: + """Stands in for a connected socket: feeds bytes in, captures bytes out.""" + + def __init__(self, request): + self.incoming = io.BytesIO(request) + self.outgoing = io.BytesIO() + + def makefile(self, mode, bufsize=-1, *args, **kwargs): + return self.incoming if "r" in mode else self.outgoing + + def close(self): + pass + + def shutdown(self, *args, **kwargs): + pass + + def sendall(self, data): + self.outgoing.write(data) + + def send(self, data): + self.outgoing.write(data) + return len(data) + + +class FakeServer: + def __init__(self, app): + self.app = app + self.server_address = ("127.0.0.1", 0) + + def log_message(self, fmt, *args): + pass + + def log_error(self, fmt, *args): + pass + + def log_request(self, *args): + pass + + +def raw_request(app, method, path, body=None, extra_headers=None): + """Run one HTTP request through CRMRequestHandler and return the response.""" + headers = {"Host": "127.0.0.1", "Connection": "close"} + payload = b"" + if body is not None: + if isinstance(body, bytes): + payload = body + elif isinstance(body, str): + payload = body.encode("utf-8") + else: + payload = json.dumps(body).encode("utf-8") + headers["Content-Length"] = str(len(payload)) + if payload and "Content-Type" not in (extra_headers or {}): + headers["Content-Type"] = "application/json" + headers.update(extra_headers or {}) + lines = ["%s %s HTTP/1.1" % (method, path)] + lines.extend("%s: %s" % (key, value) for key, value in headers.items()) + request = ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + payload + + sock = FakeSocket(request) + server_module.CRMRequestHandler(sock, ("127.0.0.1", 1234), FakeServer(app)) + raw = sock.outgoing.getvalue() + + head, _, rest = raw.partition(b"\r\n\r\n") + status_line = head.split(b"\r\n")[0].decode("latin-1") + parts = status_line.split(" ", 2) + status = int(parts[1]) + response_headers = {} + for line in head.split(b"\r\n")[1:]: + name, _, value = line.decode("latin-1").partition(":") + response_headers[name.strip().lower()] = value.strip() + length = int(response_headers.get("content-length", "0") or 0) + body_bytes = rest[:length] + data = None + if body_bytes and "application/json" in response_headers.get("content-type", ""): + data = json.loads(body_bytes.decode("utf-8")) + return status, data, response_headers, body_bytes + + +class ApiTestCase(unittest.TestCase): + """Base class with a throwaway database per test.""" + + def setUp(self): + self.tmpdir = tempfile.mkdtemp(prefix="crm-test-") + self.db_path = os.path.join(self.tmpdir, "crm.db") + self.store = server_module.Store(self.db_path) + self.app = server_module.CRMApp(self.store, static_dir=server_module.STATIC_DIR) + + def tearDown(self): + self.store.close() + shutil.rmtree(self.tmpdir, ignore_errors=True) + + def request_full(self, method, path, body=None, extra_headers=None): + """Same as :meth:`request` but also returns the raw response bytes.""" + return raw_request(self.app, method, path, body, extra_headers) + + def request(self, method, path, body=None, extra_headers=None): + status, data, headers, _ = self.request_full(method, path, body, extra_headers) + return status, data, headers + + def get(self, path): + status, data, headers, _ = self.request_full("GET", path) + return status, data, headers + + def post(self, path, body=None, **kwargs): + status, data, _, _ = self.request_full("POST", path, body, **kwargs) + return status, data + + def put(self, path, body=None): + status, data, _, _ = self.request_full("PUT", path, body) + return status, data + + def delete(self, path): + status, data, _, _ = self.request_full("DELETE", path) + return status, data + + def create(self, resource, payload): + status, data = self.post("/api/%s" % resource, payload) + self.assertEqual(status, 201, "could not create %s: %r" % (resource, data)) + return data + + def create_company(self, name="Acme", **extra): + payload = {"name": name} + payload.update(extra) + return self.create("companies", payload) + + def create_contact(self, name="Ada", **extra): + payload = {"name": name} + payload.update(extra) + return self.create("contacts", payload) + + def create_deal(self, title="Big deal", **extra): + payload = {"title": title} + payload.update(extra) + return self.create("deals", payload) + + def assert_bad_request(self, status, data, path): + self.assertEqual(status, 400, "expected 400 from %s, got %s: %r" % (path, status, data)) + self.assertIsInstance(data, dict) + self.assertTrue(data.get("error")) diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_activity.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_activity.py new file mode 100644 index 00000000..fd46f78d --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_activity.py @@ -0,0 +1,110 @@ +"""Tests for the activity log and GET /api/activity.""" + +import unittest + +from tests.base import ApiTestCase + + +class ActivityApiTest(ApiTestCase): + def entries(self, path="/api/activity"): + status, data, headers = self.get(path) + self.assertEqual(status, 200) + self.assertIsInstance(data, list) + return data, headers + + def test_empty_log(self): + data, headers = self.entries() + self.assertEqual(data, []) + self.assertEqual(headers.get("x-total-count"), "0") + + def test_create_update_delete_are_logged(self): + company = self.create_company("Acme") + self.put("/api/companies/%d" % company["id"], {"name": "Acme II"}) + self.delete("/api/companies/%d" % company["id"]) + data, headers = self.entries() + self.assertEqual(headers.get("x-total-count"), "3") + self.assertEqual([entry["action"] for entry in data], ["delete", "update", "create"]) + for entry in data: + self.assertEqual(entry["entity"], "companies") + self.assertEqual(entry["entity_id"], company["id"]) + self.assertIsNone(entry["deal_id"]) + self.assertTrue(entry["created_at"]) + self.assertEqual(data[0]["summary"], 'company "Acme II"') + self.assertEqual(data[2]["summary"], 'company "Acme"') + + def test_every_resource_is_logged(self): + contact = self.create_contact("Ada") + deal = self.create_deal("Rollout") + self.put("/api/contacts/%d" % contact["id"], {"name": "Ada L"}) + self.put("/api/deals/%d" % deal["id"], {"title": "Rollout", "stage": "won"}) + data, _ = self.entries() + self.assertEqual( + [(entry["entity"], entry["action"]) for entry in data], + [("deals", "update"), ("contacts", "update"), ("deals", "create"), ("contacts", "create")], + ) + self.assertEqual(data[0]["summary"], 'deal "Rollout"') + + def test_notes_are_logged_against_their_deal(self): + deal = self.create_deal("Rollout") + other = self.create_deal("Other") + self.post("/api/deals/%d/notes" % deal["id"], {"body": "called the client"}) + self.post("/api/deals/%d/notes" % other["id"], {"body": "unrelated"}) + data, headers = self.entries() + self.assertEqual(headers.get("x-total-count"), "4") + note_entries = [entry for entry in data if entry["entity"] == "notes"] + self.assertEqual(len(note_entries), 2) + self.assertEqual(note_entries[0]["deal_id"], other["id"]) + self.assertEqual(note_entries[1]["deal_id"], deal["id"]) + self.assertEqual(note_entries[1]["summary"], 'note "called the client"') + + def test_newest_first(self): + self.create_company("One") + self.create_company("Two") + data, _ = self.entries() + self.assertEqual([entry["summary"] for entry in data], ['company "Two"', 'company "One"']) + ids = [entry["id"] for entry in data] + self.assertEqual(ids, sorted(ids, reverse=True)) + + def test_limit_returns_newest_n(self): + for name in ("One", "Two", "Three"): + self.create_company(name) + data, headers = self.entries("/api/activity?limit=2") + self.assertEqual([entry["summary"] for entry in data], ['company "Three"', 'company "Two"']) + self.assertEqual(headers.get("x-total-count"), "3") + + def test_offset_pages_back_in_time(self): + for name in ("One", "Two", "Three"): + self.create_company(name) + data, _ = self.entries("/api/activity?limit=1&offset=2") + self.assertEqual([entry["summary"] for entry in data], ['company "One"']) + + def test_filter_by_deal(self): + deal = self.create_deal("Rollout") + self.post("/api/deals/%d/notes" % deal["id"], {"body": "first"}) + self.put("/api/deals/%d" % deal["id"], {"title": "Rollout", "stage": "won"}) + self.create_contact("Unrelated") + data, headers = self.entries("/api/activity?deal_id=%d" % deal["id"]) + self.assertEqual([entry["action"] for entry in data], ["update", "create", "create"]) + self.assertEqual(headers.get("x-total-count"), "3") + self.assertTrue(all(entry["deal_id"] == deal["id"] for entry in data)) + + def test_filter_by_entity(self): + self.create_company("One") + self.create_contact("Ada") + data, _ = self.entries("/api/activity?entity=contacts") + self.assertEqual([entry["entity"] for entry in data], ["contacts"]) + + def test_invalid_parameters_are_400(self): + for path in ("/api/activity?limit=x", "/api/activity?limit=-2", "/api/activity?deal_id=nope"): + status, payload, _ = self.get(path) + self.assertEqual(status, 400, path) + self.assertIn("error", payload) + + def test_post_is_not_allowed(self): + status, payload = self.request_full("POST", "/api/activity", {})[:2] + self.assertEqual(status, 405) + self.assertIn("error", payload) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_companies.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_companies.py new file mode 100644 index 00000000..06df6099 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_companies.py @@ -0,0 +1,123 @@ +"""Tests for /api/companies.""" + +import unittest + +from tests.base import ApiTestCase + + +class CompaniesApiTest(ApiTestCase): + def test_empty_list(self): + status, data, headers = self.get("/api/companies") + self.assertEqual(status, 200) + self.assertEqual(data, []) + self.assertEqual(headers.get("content-type"), "application/json") + + def test_create_returns_201_and_id(self): + status, data = self.post( + "/api/companies", {"name": "Acme", "website": "acme.example", "industry": "tools"} + ) + self.assertEqual(status, 201) + self.assertEqual(data["id"], 1) + self.assertEqual(data["name"], "Acme") + self.assertEqual(data["website"], "acme.example") + self.assertEqual(data["industry"], "tools") + + def test_create_minimal_and_optional_defaults(self): + company = self.create_company("Only Name") + self.assertEqual(company["website"], "") + self.assertEqual(company["industry"], "") + + def test_list_returns_all(self): + first = self.create_company("Acme") + second = self.create_company("Globex") + status, data, _ = self.get("/api/companies") + self.assertEqual(status, 200) + self.assertEqual([item["id"] for item in data], [first["id"], second["id"]]) + + def test_get_by_id(self): + company = self.create_company("Initech", industry="software") + status, data, _ = self.get("/api/companies/%d" % company["id"]) + self.assertEqual(status, 200) + self.assertEqual(data["name"], "Initech") + self.assertEqual(data["industry"], "software") + + def test_update_replaces_fields(self): + company = self.create_company("Umbrella", website="umbrella.example", industry="labs") + status, data = self.put("/api/companies/%d" % company["id"], {"name": "Umbrella Corp"}) + self.assertEqual(status, 200) + self.assertEqual(data["id"], company["id"]) + self.assertEqual(data["name"], "Umbrella Corp") + self.assertEqual(data["website"], "") + self.assertEqual(data["industry"], "") + status, reread, _ = self.get("/api/companies/%d" % company["id"]) + self.assertEqual(reread["name"], "Umbrella Corp") + + def test_delete_returns_204_and_removes(self): + company = self.create_company("Wonka") + status, data = self.delete("/api/companies/%d" % company["id"]) + self.assertEqual(status, 204) + self.assertIsNone(data) + status, data, _ = self.get("/api/companies/%d" % company["id"]) + self.assertEqual(status, 404) + self.assertIn("error", data) + status, listed, _ = self.get("/api/companies") + self.assertEqual(listed, []) + + def test_search_is_case_insensitive_substring(self): + self.create_company("Acme Industries") + self.create_company("Globex") + status, data, _ = self.get("/api/companies?q=acme") + self.assertEqual(status, 200) + self.assertEqual([item["name"] for item in data], ["Acme Industries"]) + status, data, _ = self.get("/api/companies?q=ME%20IND") + self.assertEqual([item["name"] for item in data], ["Acme Industries"]) + status, data, _ = self.get("/api/companies?q=nothing") + self.assertEqual(data, []) + + def test_unknown_id_is_404(self): + for method in ("GET", "PUT", "DELETE"): + if method == "PUT": + status, data = self.put("/api/companies/4242", {"name": "Ghost"}) + else: + status, data, _ = self.request(method, "/api/companies/4242") + self.assertEqual(status, 404, method) + self.assertEqual(data, {"error": data["error"]}) + self.assertTrue(data["error"]) + + def test_missing_name_is_400(self): + for payload in ({}, {"website": "x.example"}, {"name": ""}, {"name": " "}, {"name": None}): + status, data = self.post("/api/companies", payload) + self.assert_bad_request(status, data, "POST /api/companies %r" % (payload,)) + + def test_wrong_types_are_400(self): + for payload in ( + {"name": 5}, + {"name": True}, + {"name": "ok", "website": 12}, + {"name": "ok", "industry": ["a"]}, + ): + status, data = self.post("/api/companies", payload) + self.assert_bad_request(status, data, "POST /api/companies %r" % (payload,)) + + def test_invalid_json_body_is_400(self): + status, data, _ = self.request("POST", "/api/companies", "{not json") + self.assertEqual(status, 400) + self.assertIn("error", data) + + def test_json_array_body_is_400(self): + status, data = self.post("/api/companies", [1, 2, 3]) + self.assert_bad_request(status, data, "POST /api/companies") + + def test_update_requires_name(self): + company = self.create_company("Hooli") + status, data = self.put("/api/companies/%d" % company["id"], {"website": "hooli.example"}) + self.assert_bad_request(status, data, "PUT company") + + def test_method_not_allowed(self): + status, data, _ = self.request("DELETE", "/api/companies") + self.assertEqual(status, 405) + self.assertIn("error", data) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_contacts.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_contacts.py new file mode 100644 index 00000000..bf342551 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_contacts.py @@ -0,0 +1,100 @@ +"""Tests for /api/contacts.""" + +import unittest + +from tests.base import ApiTestCase + + +class ContactsApiTest(ApiTestCase): + def test_empty_list(self): + status, data, _ = self.get("/api/contacts") + self.assertEqual(status, 200) + self.assertEqual(data, []) + + def test_create_full_record(self): + company = self.create_company("Acme") + status, data = self.post( + "/api/contacts", + { + "name": "Ada Lovelace", + "email": "ada@acme.example", + "phone": "+1 555 0100", + "company_id": company["id"], + }, + ) + self.assertEqual(status, 201) + self.assertEqual(data["id"], 1) + self.assertEqual(data["name"], "Ada Lovelace") + self.assertEqual(data["email"], "ada@acme.example") + self.assertEqual(data["phone"], "+1 555 0100") + self.assertEqual(data["company_id"], company["id"]) + + def test_create_without_company(self): + contact = self.create_contact("Grace") + self.assertIsNone(contact["company_id"]) + + def test_get_update_delete(self): + contact = self.create_contact("Grace", email="grace@example.com") + status, data, _ = self.get("/api/contacts/%d" % contact["id"]) + self.assertEqual(status, 200) + self.assertEqual(data["email"], "grace@example.com") + + other = self.create_company("Raytheon") + status, data = self.put( + "/api/contacts/%d" % contact["id"], + {"name": "Grace Hopper", "email": "grace@raytheon.example", "company_id": other["id"]}, + ) + self.assertEqual(status, 200) + self.assertEqual(data["name"], "Grace Hopper") + self.assertEqual(data["company_id"], other["id"]) + self.assertEqual(data["phone"], "") + + status, _ = self.delete("/api/contacts/%d" % contact["id"]) + self.assertEqual(status, 204) + status, data, _ = self.get("/api/contacts/%d" % contact["id"]) + self.assertEqual(status, 404) + + def test_search_matches_name_and_email(self): + self.create_contact("Ada Lovelace", email="ada@example.com") + self.create_contact("Alan Turing", email="alan@bletchley.example") + for query, expected in ( + ("ada", ["Ada Lovelace"]), + ("ADA", ["Ada Lovelace"]), + ("bletchley", ["Alan Turing"]), + ("turing", ["Alan Turing"]), + ("zzz", []), + ): + status, data, _ = self.get("/api/contacts?q=%s" % query) + self.assertEqual(status, 200) + self.assertEqual([item["name"] for item in data], expected, query) + + def test_missing_name_is_400(self): + for payload in ({}, {"name": ""}, {"name": 3}, {"email": "no-name@example.com"}): + status, data = self.post("/api/contacts", payload) + self.assert_bad_request(status, data, "POST /api/contacts %r" % (payload,)) + + def test_unknown_company_is_400(self): + status, data = self.post("/api/contacts", {"name": "Nobody", "company_id": 999}) + self.assert_bad_request(status, data, "POST /api/contacts unknown company") + + def test_unknown_id_is_404(self): + status, data, _ = self.get("/api/contacts/1234") + self.assertEqual(status, 404) + self.assertIn("error", data) + status, data = self.put("/api/contacts/1234", {"name": "Ghost"}) + self.assertEqual(status, 404) + status, data = self.delete("/api/contacts/1234") + self.assertEqual(status, 404) + + def test_deleting_company_clears_reference_but_keeps_contact(self): + company = self.create_company("Acme") + contact = self.create_contact("Ada", company_id=company["id"]) + status, _ = self.delete("/api/companies/%d" % company["id"]) + self.assertEqual(status, 204) + status, data, _ = self.get("/api/contacts/%d" % contact["id"]) + self.assertEqual(status, 200) + self.assertIsNone(data["company_id"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_csv_export.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_csv_export.py new file mode 100644 index 00000000..68bc9482 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_csv_export.py @@ -0,0 +1,81 @@ +"""Tests for the CSV export endpoints.""" + +import csv +import io +import unittest + +from tests.base import ApiTestCase + + +class CsvExportTest(ApiTestCase): + def download(self, path): + status, _, headers, body = self.request_full("GET", path) + self.assertEqual(status, 200) + self.assertTrue(headers.get("content-type", "").startswith("text/csv"), headers) + return list(csv.reader(io.StringIO(body.decode("utf-8")))) + + def test_header_row_only_when_empty(self): + for resource, columns in ( + ("companies", ["id", "name", "website", "industry"]), + ("contacts", ["id", "name", "email", "phone", "company_id"]), + ("deals", ["id", "title", "amount", "stage", "company_id", "contact_id", "created_at"]), + ): + rows = self.download("/api/%s.csv" % resource) + self.assertEqual(rows, [columns], resource) + + def test_rows_match_the_api(self): + company = self.create_company("Acme", website="acme.example", industry="tools") + contact = self.create_contact("Ada", email="ada@acme.example", company_id=company["id"]) + deal = self.create_deal("Rollout", amount=1500, stage="won", company_id=company["id"], contact_id=contact["id"]) + + rows = self.download("/api/companies.csv") + self.assertEqual(rows[1], [str(company["id"]), "Acme", "acme.example", "tools"]) + rows = self.download("/api/contacts.csv") + self.assertEqual(rows[1], [str(contact["id"]), "Ada", "ada@acme.example", "", str(company["id"])]) + rows = self.download("/api/deals.csv") + self.assertEqual(rows[1][:6], [str(deal["id"]), "Rollout", "1500.0", "won", str(company["id"]), str(contact["id"])]) + + def test_quoting_of_tricky_values(self): + self.create_company('Smith, Jane & "Associates"', industry="line\nbreak") + rows = self.download("/api/companies.csv") + self.assertEqual(len(rows), 2) + self.assertEqual(rows[1][1], 'Smith, Jane & "Associates"') + self.assertEqual(rows[1][3], "line\nbreak") + status, _, _, body = self.request_full("GET", "/api/companies.csv") + self.assertIn(b'"Smith, Jane & ""Associates"""', body) + + def test_null_references_become_empty_cells(self): + self.create_contact("Solo") + rows = self.download("/api/contacts.csv") + self.assertEqual(rows[1], ["1", "Solo", "", "", ""]) + + def test_filters_apply(self): + self.create_deal("Alpha", stage="won") + self.create_deal("Beta", stage="lead") + rows = self.download("/api/deals.csv?stage=won") + self.assertEqual(len(rows), 2) + self.assertEqual(rows[1][1], "Alpha") + rows = self.download("/api/deals.csv?q=beta&stage=lead") + self.assertEqual(len(rows), 2) + self.assertEqual(rows[1][1], "Beta") + + def test_pagination_applies(self): + for index in range(3): + self.create_company("C%d" % index) + rows = self.download("/api/companies.csv?limit=1&offset=1") + self.assertEqual(len(rows), 2) + self.assertEqual(rows[1][1], "C1") + + def test_unknown_resource_is_404(self): + status, data, _ = self.get("/api/nope.csv") + self.assertEqual(status, 404) + self.assertIn("error", data) + + def test_wrong_method_is_405(self): + status, data = self.request_full("POST", "/api/companies.csv", {})[:2] + self.assertEqual(status, 405) + self.assertIn("error", data) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_deals.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_deals.py new file mode 100644 index 00000000..1851c218 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_deals.py @@ -0,0 +1,150 @@ +"""Tests for /api/deals.""" + +import unittest + +from tests.base import ApiTestCase + +STAGES = ("lead", "qualified", "proposal", "won", "lost") + + +class DealsApiTest(ApiTestCase): + def test_empty_list(self): + status, data, _ = self.get("/api/deals") + self.assertEqual(status, 200) + self.assertEqual(data, []) + + def test_create_defaults(self): + status, data = self.post("/api/deals", {"title": "First deal"}) + self.assertEqual(status, 201) + self.assertEqual(data["title"], "First deal") + self.assertEqual(data["amount"], 0) + self.assertEqual(data["stage"], "lead") + self.assertIsNone(data["company_id"]) + self.assertIsNone(data["contact_id"]) + + def test_create_full_record(self): + company = self.create_company("Acme") + contact = self.create_contact("Ada", company_id=company["id"]) + status, data = self.post( + "/api/deals", + { + "title": "Enterprise rollout", + "amount": 12500.5, + "stage": "proposal", + "company_id": company["id"], + "contact_id": contact["id"], + }, + ) + self.assertEqual(status, 201) + self.assertEqual(data["amount"], 12500.5) + self.assertEqual(data["stage"], "proposal") + self.assertEqual(data["company_id"], company["id"]) + self.assertEqual(data["contact_id"], contact["id"]) + + def test_every_stage_is_accepted(self): + for index, stage in enumerate(STAGES): + status, data = self.post("/api/deals", {"title": "Deal %d" % index, "stage": stage}) + self.assertEqual(status, 201, stage) + self.assertEqual(data["stage"], stage) + + def test_invalid_stage_is_400_on_create(self): + for stage in ("closed", "Lead", "", " ", None, 3): + if stage is None: + continue # absent stage falls back to the default + status, data = self.post("/api/deals", {"title": "Bad stage", "stage": stage}) + self.assert_bad_request(status, data, "POST deal stage=%r" % (stage,)) + + def test_invalid_stage_is_400_on_update(self): + deal = self.create_deal("Move me") + status, data = self.put("/api/deals/%d" % deal["id"], {"title": "Move me", "stage": "someday"}) + self.assert_bad_request(status, data, "PUT deal stage") + status, current, _ = self.get("/api/deals/%d" % deal["id"]) + self.assertEqual(current["stage"], "lead") + + def test_update_moves_stage_and_amount(self): + deal = self.create_deal("Negotiation", amount=100) + status, data = self.put("/api/deals/%d" % deal["id"], {"title": "Negotiation", "amount": 250, "stage": "won"}) + self.assertEqual(status, 200) + self.assertEqual(data["stage"], "won") + self.assertEqual(data["amount"], 250) + + def test_missing_title_is_400(self): + for payload in ({}, {"title": ""}, {"title": 7}, {"amount": 10}): + status, data = self.post("/api/deals", payload) + self.assert_bad_request(status, data, "POST /api/deals %r" % (payload,)) + + def test_bad_amount_is_400(self): + for amount in ("1000", -1, -0.01, "abc", True, [5]): + status, data = self.post("/api/deals", {"title": "Bad amount", "amount": amount}) + self.assert_bad_request(status, data, "POST deal amount=%r" % (amount,)) + + def test_zero_amount_is_allowed(self): + status, data = self.post("/api/deals", {"title": "Free trial", "amount": 0}) + self.assertEqual(status, 201) + self.assertEqual(data["amount"], 0) + + def test_stage_filter(self): + self.create_deal("A", stage="won") + self.create_deal("B", stage="lead") + self.create_deal("C", stage="won") + status, data, _ = self.get("/api/deals?stage=won") + self.assertEqual(status, 200) + self.assertEqual([item["title"] for item in data], ["A", "C"]) + + def test_text_filter_matches_title(self): + self.create_deal("Alpha contract") + self.create_deal("Beta renewal") + status, data, _ = self.get("/api/deals?q=beta") + self.assertEqual([item["title"] for item in data], ["Beta renewal"]) + + def test_stage_and_text_filters_combine(self): + self.create_deal("Alpha win", stage="won") + self.create_deal("Alpha loss", stage="lost") + self.create_deal("Gamma win", stage="won") + status, data, _ = self.get("/api/deals?stage=won&q=alpha") + self.assertEqual(status, 200) + self.assertEqual([item["title"] for item in data], ["Alpha win"]) + + def test_unknown_id_is_404(self): + status, data, _ = self.get("/api/deals/777") + self.assertEqual(status, 404) + self.assertIn("error", data) + status, data = self.put("/api/deals/777", {"title": "Ghost"}) + self.assertEqual(status, 404) + status, data = self.delete("/api/deals/777") + self.assertEqual(status, 404) + + def test_delete_deal(self): + deal = self.create_deal("Doomed") + status, _ = self.delete("/api/deals/%d" % deal["id"]) + self.assertEqual(status, 204) + status, data, _ = self.get("/api/deals") + self.assertEqual(data, []) + + def test_deleting_company_keeps_deal_and_clears_reference(self): + company = self.create_company("Acme") + deal = self.create_deal("Kept", company_id=company["id"]) + status, _ = self.delete("/api/companies/%d" % company["id"]) + self.assertEqual(status, 204) + status, data, _ = self.get("/api/deals/%d" % deal["id"]) + self.assertEqual(status, 200) + self.assertIsNone(data["company_id"]) + + def test_deleting_contact_keeps_deal_and_clears_reference(self): + contact = self.create_contact("Ada") + deal = self.create_deal("Kept", contact_id=contact["id"]) + status, _ = self.delete("/api/contacts/%d" % contact["id"]) + self.assertEqual(status, 204) + status, data, _ = self.get("/api/deals/%d" % deal["id"]) + self.assertEqual(status, 200) + self.assertIsNone(data["contact_id"]) + + def test_unknown_references_are_400(self): + status, data = self.post("/api/deals", {"title": "Bad refs", "company_id": 404}) + self.assert_bad_request(status, data, "unknown company_id") + status, data = self.post("/api/deals", {"title": "Bad refs", "contact_id": "x"}) + self.assert_bad_request(status, data, "non integer contact_id") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_live_server.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_live_server.py new file mode 100644 index 00000000..d4d06e53 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_live_server.py @@ -0,0 +1,115 @@ +"""End-to-end checks against a real listening server. + +These are skipped automatically when the environment forbids opening a +listening socket (for example inside a restrictive sandbox); every endpoint is +also covered by the in-process tests in the other modules. +""" + +import json +import os +import shutil +import tempfile +import threading +import unittest +import urllib.error +import urllib.request + +from tests.base import ROOT # noqa: F401 (adds the project root to sys.path) + +import server as server_module + + +def _start_server(db_path): + return server_module.create_server(0, db_path) + + +class LiveServerTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmpdir = tempfile.mkdtemp(prefix="crm-live-") + try: + cls.server = _start_server(os.path.join(cls.tmpdir, "live.db")) + except (PermissionError, OSError) as exc: + shutil.rmtree(cls.tmpdir, ignore_errors=True) + raise unittest.SkipTest("cannot open a listening socket: %s" % exc) + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + cls.base = "http://127.0.0.1:%d" % cls.server.server_address[1] + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.thread.join(timeout=5) + cls.server.server_close() + shutil.rmtree(cls.tmpdir, ignore_errors=True) + + def call(self, method, path, payload=None): + data = None if payload is None else json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + self.base + path, + data=data, + method=method, + headers={"Content-Type": "application/json"} if data else {}, + ) + try: + with urllib.request.urlopen(request, timeout=10) as response: + body = response.read() + status = response.status + except urllib.error.HTTPError as exc: + body = exc.read() + status = exc.code + parsed = json.loads(body.decode("utf-8")) if body else None + return status, parsed + + def test_full_round_trip(self): + status, company = self.call("POST", "/api/companies", {"name": "Live Co", "industry": "tests"}) + self.assertEqual(status, 201) + self.assertGreater(company["id"], 0) + + status, contact = self.call( + "POST", "/api/contacts", {"name": "Ada", "email": "ada@live.example", "company_id": company["id"]} + ) + self.assertEqual(status, 201) + + status, deal = self.call( + "POST", "/api/deals", {"title": "Live deal", "amount": 500, "company_id": company["id"]} + ) + self.assertEqual(status, 201) + + status, note = self.call("POST", "/api/deals/%d/notes" % deal["id"], {"body": "kickoff"}) + self.assertEqual(status, 201) + status, notes = self.call("GET", "/api/deals/%d/notes" % deal["id"]) + self.assertEqual(status, 200) + self.assertEqual([item["body"] for item in notes], ["kickoff"]) + + status, deals = self.call("GET", "/api/deals?stage=lead&q=live") + self.assertEqual(status, 200) + self.assertEqual(len(deals), 1) + + status, pipeline = self.call("GET", "/api/pipeline") + self.assertEqual(status, 200) + self.assertEqual(pipeline["lead"]["count"], 1) + self.assertEqual(pipeline["lead"]["amount"], 500) + + status, updated = self.call("PUT", "/api/deals/%d" % deal["id"], {"title": "Live deal", "stage": "won", "amount": 500}) + self.assertEqual(status, 200) + self.assertEqual(updated["stage"], "won") + + status, _ = self.call("DELETE", "/api/companies/%d" % company["id"]) + self.assertEqual(status, 204) + status, deals = self.call("GET", "/api/deals") + self.assertEqual(len(deals), 1) + self.assertIsNone(deals[0]["company_id"]) + + def test_index_and_errors(self): + with urllib.request.urlopen(self.base + "/", timeout=10) as response: + self.assertEqual(response.status, 200) + self.assertIn("text/html", response.headers.get("Content-Type", "")) + with self.assertRaises(urllib.error.HTTPError) as ctx: + urllib.request.urlopen(self.base + "/api/companies/424242", timeout=10) + self.assertEqual(ctx.exception.code, 404) + self.assertIn("error", json.loads(ctx.exception.read().decode("utf-8"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_notes.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_notes.py new file mode 100644 index 00000000..9583800e --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_notes.py @@ -0,0 +1,65 @@ +"""Tests for GET/POST /api/deals/{id}/notes.""" + +import unittest + +from tests.base import ApiTestCase + + +class NotesApiTest(ApiTestCase): + def test_empty_notes(self): + deal = self.create_deal("Noted") + status, data, headers = self.get("/api/deals/%d/notes" % deal["id"]) + self.assertEqual(status, 200) + self.assertEqual(data, []) + self.assertEqual(headers.get("content-type"), "application/json") + + def test_create_note_returns_201(self): + deal = self.create_deal("Noted") + status, data = self.post("/api/deals/%d/notes" % deal["id"], {"body": "Called the client"}) + self.assertEqual(status, 201) + self.assertEqual(data["deal_id"], deal["id"]) + self.assertEqual(data["body"], "Called the client") + self.assertIsInstance(data["id"], int) + self.assertTrue(data["created_at"]) + + def test_notes_are_listed_in_order_and_scoped_to_deal(self): + first = self.create_deal("One") + second = self.create_deal("Two") + self.post("/api/deals/%d/notes" % first["id"], {"body": "one-a"}) + self.post("/api/deals/%d/notes" % second["id"], {"body": "two-a"}) + self.post("/api/deals/%d/notes" % first["id"], {"body": "one-b"}) + status, data, _ = self.get("/api/deals/%d/notes" % first["id"]) + self.assertEqual([note["body"] for note in data], ["one-a", "one-b"]) + status, data, _ = self.get("/api/deals/%d/notes" % second["id"]) + self.assertEqual([note["body"] for note in data], ["two-a"]) + + def test_body_is_required(self): + deal = self.create_deal("Noted") + for payload in (None, {}, {"body": ""}, {"body": " "}, {"body": 5}, {"note": "x"}): + status, data = self.post("/api/deals/%d/notes" % deal["id"], payload) + self.assert_bad_request(status, data, "POST notes %r" % (payload,)) + + def test_unknown_deal_is_404(self): + status, data, _ = self.get("/api/deals/999/notes") + self.assertEqual(status, 404) + self.assertIn("error", data) + status, data = self.post("/api/deals/999/notes", {"body": "hello"}) + self.assertEqual(status, 404) + + def test_notes_route_rejects_other_methods(self): + deal = self.create_deal("Noted") + status, data, _ = self.request("DELETE", "/api/deals/%d/notes" % deal["id"]) + self.assertEqual(status, 405) + self.assertIn("error", data) + + def test_deleting_deal_removes_its_notes(self): + deal = self.create_deal("Doomed") + self.post("/api/deals/%d/notes" % deal["id"], {"body": "bye"}) + status, _ = self.delete("/api/deals/%d" % deal["id"]) + self.assertEqual(status, 204) + status, data, _ = self.get("/api/deals/%d/notes" % deal["id"]) + self.assertEqual(status, 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pagination.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pagination.py new file mode 100644 index 00000000..a4644911 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pagination.py @@ -0,0 +1,87 @@ +"""Tests for ?limit=N&offset=M and the X-Total-Count header.""" + +import unittest + +from tests.base import ApiTestCase + + +class PaginationTest(ApiTestCase): + def setUp(self): + super().setUp() + for index in range(1, 6): + self.create_company("Company %d" % index) + + def test_default_returns_everything(self): + status, data, headers = self.get("/api/companies") + self.assertEqual(status, 200) + self.assertEqual(len(data), 5) + self.assertEqual(headers.get("x-total-count"), "5") + + def test_limit(self): + status, data, headers = self.get("/api/companies?limit=2") + self.assertEqual(status, 200) + self.assertEqual([item["name"] for item in data], ["Company 1", "Company 2"]) + self.assertEqual(headers.get("x-total-count"), "5") + + def test_offset(self): + status, data, headers = self.get("/api/companies?offset=3") + self.assertEqual(status, 200) + self.assertEqual([item["name"] for item in data], ["Company 4", "Company 5"]) + self.assertEqual(headers.get("x-total-count"), "5") + + def test_limit_and_offset(self): + status, data, headers = self.get("/api/companies?limit=2&offset=2") + self.assertEqual(status, 200) + self.assertEqual([item["name"] for item in data], ["Company 3", "Company 4"]) + self.assertEqual(headers.get("x-total-count"), "5") + + def test_offset_past_the_end(self): + status, data, headers = self.get("/api/companies?limit=2&offset=99") + self.assertEqual(status, 200) + self.assertEqual(data, []) + self.assertEqual(headers.get("x-total-count"), "5") + + def test_total_counts_filters(self): + self.create_company("Other") + status, data, headers = self.get("/api/companies?q=company&limit=2") + self.assertEqual(len(data), 2) + self.assertEqual(headers.get("x-total-count"), "5") + + def test_contacts_and_deals_are_paginated(self): + for index in range(3): + self.create_contact("Contact %d" % index) + self.create_deal("Deal %d" % index, stage="won" if index == 2 else "lead") + status, data, headers = self.get("/api/contacts?limit=1") + self.assertEqual(len(data), 1) + self.assertEqual(headers.get("x-total-count"), "3") + status, data, headers = self.get("/api/deals?stage=lead&limit=1&offset=1") + self.assertEqual([item["title"] for item in data], ["Deal 1"]) + self.assertEqual(headers.get("x-total-count"), "2") + + def test_notes_are_paginated(self): + deal = self.create_deal("Noted") + for index in range(4): + self.post("/api/deals/%d/notes" % deal["id"], {"body": "note %d" % index}) + status, data, headers = self.get("/api/deals/%d/notes?limit=2&offset=1" % deal["id"]) + self.assertEqual(status, 200) + self.assertEqual([note["body"] for note in data], ["note 1", "note 2"]) + self.assertEqual(headers.get("x-total-count"), "4") + status, data, headers = self.get("/api/deals/%d/notes" % deal["id"]) + self.assertEqual(len(data), 4) + self.assertEqual(headers.get("x-total-count"), "4") + + def test_invalid_values_are_400(self): + for path in ( + "/api/companies?limit=abc", + "/api/companies?limit=-1", + "/api/companies?offset=-5", + "/api/companies?offset=x", + "/api/deals?limit=1.5", + ): + status, data, _ = self.get(path) + self.assertEqual(status, 400, path) + self.assertIn("error", data) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pipeline.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pipeline.py new file mode 100644 index 00000000..bb835603 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_pipeline.py @@ -0,0 +1,54 @@ +"""Tests for GET /api/pipeline.""" + +import unittest + +from tests.base import ApiTestCase + +STAGES = ("lead", "qualified", "proposal", "won", "lost") + + +class PipelineApiTest(ApiTestCase): + def test_empty_pipeline_has_every_stage(self): + status, data, headers = self.get("/api/pipeline") + self.assertEqual(status, 200) + self.assertEqual(headers.get("content-type"), "application/json") + self.assertEqual(sorted(data), sorted(STAGES)) + for stage in STAGES: + self.assertEqual(data[stage], {"count": 0, "amount": 0}) + + def test_counts_and_totals(self): + self.create_deal("A", amount=100, stage="lead") + self.create_deal("B", amount=250.5, stage="lead") + self.create_deal("C", amount=900, stage="won") + status, data, _ = self.get("/api/pipeline") + self.assertEqual(status, 200) + self.assertEqual(data["lead"], {"count": 2, "amount": 350.5}) + self.assertEqual(data["won"], {"count": 1, "amount": 900}) + self.assertEqual(data["qualified"]["count"], 0) + self.assertEqual(data["proposal"]["amount"], 0) + self.assertEqual(data["lost"]["count"], 0) + + def test_pipeline_ignores_filters(self): + self.create_deal("Alpha", amount=10, stage="won") + status, data, _ = self.get("/api/pipeline?stage=lead&q=zzz") + self.assertEqual(status, 200) + self.assertEqual(data["won"]["count"], 1) + + def test_pipeline_reflects_updates_and_deletes(self): + deal = self.create_deal("Moving", amount=42, stage="lead") + self.put("/api/deals/%d" % deal["id"], {"title": "Moving", "amount": 42, "stage": "lost"}) + status, data, _ = self.get("/api/pipeline") + self.assertEqual(data["lead"]["count"], 0) + self.assertEqual(data["lost"], {"count": 1, "amount": 42}) + self.delete("/api/deals/%d" % deal["id"]) + status, data, _ = self.get("/api/pipeline") + self.assertEqual(data["lost"]["count"], 0) + + def test_pipeline_rejects_post(self): + status, data, _ = self.request("POST", "/api/pipeline", {}) + self.assertEqual(status, 405) + self.assertIn("error", data) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_robustness.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_robustness.py new file mode 100644 index 00000000..84b45c36 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_robustness.py @@ -0,0 +1,123 @@ +"""Tests for the hardening fixes: body limits, error mapping, atomic logging.""" + +import contextlib +import io +import sqlite3 +import unittest + +from tests.base import ApiTestCase + +import handlers + + +class BodyLimitTest(ApiTestCase): + def test_oversized_body_is_rejected(self): + original = handlers.MAX_BODY_BYTES + handlers.MAX_BODY_BYTES = 64 + try: + status, data = self.post("/api/companies", {"name": "x" * 200}) + self.assertEqual(status, 413) + self.assertIn("larger than 64 bytes", data["error"]) + finally: + handlers.MAX_BODY_BYTES = original + + def test_body_at_the_limit_is_accepted(self): + original = handlers.MAX_BODY_BYTES + handlers.MAX_BODY_BYTES = 4096 + try: + status, _ = self.post("/api/companies", {"name": "y" * 200}) + self.assertEqual(status, 201) + finally: + handlers.MAX_BODY_BYTES = original + + def test_negative_content_length_is_400(self): + status, data, _ = self.request_full("POST", "/api/companies", {}, {"Content-Length": "-5"})[:3] + self.assertEqual(status, 400) + self.assertIn("Content-Length", data["error"]) + + def test_non_numeric_content_length_is_400(self): + status, data, _ = self.request_full("POST", "/api/companies", {}, {"Content-Length": "many"})[:3] + self.assertEqual(status, 400) + self.assertIn("Content-Length", data["error"]) + + +class ErrorMappingTest(ApiTestCase): + def silence(self): + return contextlib.redirect_stderr(io.StringIO()) + + def test_unexpected_errors_do_not_leak_internals(self): + def boom(*args, **kwargs): + raise sqlite3.OperationalError("no such table: secret_internal_stuff") + + self.store.list = boom + with self.silence(): + status, data, _ = self.get("/api/companies") + self.assertEqual(status, 500) + self.assertEqual(data, {"error": "internal server error"}) + self.assertNotIn("secret_internal_stuff", str(data)) + + def test_integrity_conflicts_answer_409(self): + def boom(*args, **kwargs): + raise sqlite3.IntegrityError("UNIQUE constraint failed") + + self.store.create = boom + with self.silence(): + status, data = self.post("/api/companies", {"name": "Conflict"}) + self.assertEqual(status, 409) + self.assertEqual(data, {"error": "the change conflicts with existing data"}) + + def test_known_errors_keep_their_status(self): + with self.silence(): + status, data, _ = self.get("/api/companies/4242") + self.assertEqual(status, 404) + self.assertIn("error", data) + + +class AtomicActivityTest(ApiTestCase): + def activity_for(self, entity, entity_id): + entries, _total = self.store.list_activity(entity=entity) + return [entry for entry in entries if entry["entity_id"] == entity_id] + + def test_each_mutation_writes_exactly_one_entry(self): + company = self.create_company("Acme") + self.assertEqual(len(self.activity_for("companies", company["id"])), 1) + self.put("/api/companies/%d" % company["id"], {"name": "Acme II"}) + self.assertEqual(len(self.activity_for("companies", company["id"])), 2) + self.delete("/api/companies/%d" % company["id"]) + self.assertEqual(len(self.activity_for("companies", company["id"])), 3) + + def test_rejected_request_leaves_no_trace(self): + deal = self.create_deal("Rollout") + before = len(self.activity_for("deals", deal["id"])) + self.put("/api/deals/%d" % deal["id"], {"title": "Rollout", "stage": "bogus"}) + self.assertEqual(len(self.activity_for("deals", deal["id"])), before) + + def test_failed_database_write_rolls_back_the_log(self): + company = self.create_company("Acme") + contact = self.create_contact("Ada", company_id=company["id"]) + before = len(self.activity_for("contacts", contact["id"])) + with self.assertRaises(sqlite3.IntegrityError): + self.store.update("contacts", contact["id"], {"company_id": 999}, log_action="update") + self.assertEqual(len(self.activity_for("contacts", contact["id"])), before) + stored = self.store.get("contacts", contact["id"]) + self.assertEqual(stored["company_id"], company["id"]) + + def test_note_and_its_log_entry_are_written_together(self): + deal = self.create_deal("Rollout") + self.post("/api/deals/%d/notes" % deal["id"], {"body": "kickoff"}) + notes, _total = self.store.list_notes(deal["id"]) + entries = self.activity_for("notes", notes[0]["id"]) + self.assertEqual(len(notes), 1) + self.assertEqual(len(entries), 1) + self.assertEqual(entries[0]["deal_id"], deal["id"]) + + def test_failed_mutation_leaves_no_transaction_open(self): + company = self.create_company("Acme") + contact = self.create_contact("Ada", company_id=company["id"]) + with self.assertRaises(sqlite3.IntegrityError): + self.store.update("contacts", contact["id"], {"company_id": 999}, log_action="update") + self.assertFalse(self.store.conn.in_transaction) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_server_setup.py b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_server_setup.py new file mode 100644 index 00000000..89cddd23 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/reference/overlay/tests/test_server_setup.py @@ -0,0 +1,101 @@ +"""Tests for the front-end route, unknown routes and server configuration.""" + +import os +import unittest + +from tests.base import ApiTestCase + +import server as server_module + + +class StaticRoutesTest(ApiTestCase): + def test_root_serves_single_page_app(self): + status, _, headers, body = self.request_full("GET", "/") + self.assertEqual(status, 200) + self.assertTrue(headers.get("content-type", "").startswith("text/html")) + self.assertIn(b" max_len: + raise ValidationError("%s must be at most %d characters" % (field, max_len)) + return text + + +def clean_email(value, field="email"): + """Validate an optional email address.""" + text = clean_text(value, field) + if text and not EMAIL_RE.match(text): + raise ValidationError("%s is not a valid email address" % field) + return text + + +def clean_amount(value, field="amount"): + """Validate an optional non-negative number, defaulting to 0.""" + if value is None: + return 0.0 + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValidationError("%s must be a number" % field) + amount = float(value) + if amount < 0: + raise ValidationError("%s must be greater than or equal to 0" % field) + return amount + + +def clean_stage(value, stages, field="stage", default=None): + """Validate a deal stage, defaulting when the key is absent.""" + if value is None: + return default + if isinstance(value, bool) or not isinstance(value, str) or value not in stages: + raise ValidationError("%s must be one of: %s" % (field, ", ".join(stages))) + return value + + +def clean_reference(store, value, table, field, entity="record"): + """Validate an optional foreign key against an existing row.""" + if value is None or value == "": + return None + if isinstance(value, bool) or not isinstance(value, int): + raise ValidationError("%s must be an integer" % field) + if not store.exists(table, value): + raise ValidationError("%s does not reference an existing %s" % (field, entity)) + return value + + +def require_object(body): + """Accept only a parsed JSON object as a request body.""" + if body is None: + raise ValidationError("request body is required") + if not isinstance(body, dict): + raise ValidationError("request body must be a JSON object") + return body + + +def parse_id(raw_id): + """Parse a record id taken from the URL.""" + try: + value = int(raw_id) + except (TypeError, ValueError): + raise NotFoundError("invalid id %r" % (raw_id,)) + if value < 1: + raise NotFoundError("invalid id %r" % (raw_id,)) + return value + + +def parse_int_param(raw_value, field, minimum): + """Parse an integer query parameter such as limit or offset.""" + try: + value = int(raw_value) + except (TypeError, ValueError): + raise ValidationError("%s must be an integer" % field) + if value < minimum: + raise ValidationError("%s must be greater than or equal to %d" % (field, minimum)) + return value diff --git a/scripts/e2e/codex/tasks/crm/task.md b/scripts/e2e/codex/tasks/crm/task.md new file mode 100644 index 00000000..5aa10e47 --- /dev/null +++ b/scripts/e2e/codex/tasks/crm/task.md @@ -0,0 +1,38 @@ +--- +id: crm +title: Small CRM web app (two phases) +kind: create +expected_rounds: 60-110 +--- +# Small CRM web app (two phases) + +Existing task of docs/e2e-run.md (jobs 945*), prompt text unchanged from `scripts/e2e/codex/prompt-crm.txt` (sha256 2ab4d92db393334f1ac953086116cefb9744b522b98bfd4ea6efd7e02e319af9 of the file). Empty seed. Acceptance: `accept.py` = `crm_acceptance.py` (21 checks, REST API plus the app's own unittest suite) run on a copy of the workspace. + +## Prompt + +Build a small CRM web application in the current directory using ONLY Python 3 standard library modules (http.server, sqlite3, json, unittest, urllib): there is no network and no package can be installed. + +Layout and commands (fixed, an acceptance script will rely on them): +- server.py: running `python3 server.py` starts an HTTP server on the port in the environment variable PORT (default 8000), bound to 127.0.0.1, with data stored in the SQLite file given by the environment variable CRM_DB (default crm.db). It creates the tables on first start. +- tests/: a unittest suite; `python3 -m unittest discover -s tests` must run offline and pass. Cover every endpoint. +- README.md: how to run, the API, and the data model. +- static/index.html (served at GET /): a single-page front-end (plain HTML + JavaScript, no libraries) with a companies list, a contacts list, a deals board with one column per stage, a search box that filters the lists, and forms to create, edit and delete records and to add notes to a deal. + +REST API (JSON bodies and responses, Content-Type application/json): +- Resources: /api/companies (name required, website, industry), /api/contacts (name required, email, phone, company_id optional), /api/deals (title required, amount number default 0, stage, company_id optional, contact_id optional), notes: GET and POST /api/deals/{id}/notes (body required). +- For each of companies, contacts, deals: GET /api/ lists all records (supports ?q=text, a case-insensitive substring filter on the name/title/email fields, and for deals also ?stage=); POST /api/ creates and returns 201 with the record including its integer id; GET /api//{id}; PUT /api//{id} replaces the editable fields and returns 200 with the record; DELETE /api//{id} returns 204. Unknown ids return 404 with {"error": "..."}; invalid input returns 400 with {"error": "..."}. +- Deal stages are exactly: lead, qualified, proposal, won, lost (default lead). PUT with another stage value returns 400. Deleting a company or contact must not delete deals; it clears the reference. +- GET /api/deals?stage=won&q=... combines both filters. GET /api/pipeline returns {"lead": {"count": n, "amount": total}, ...} for every stage. + +Work step by step, run the tests and fix failures. When all tests pass and the server starts and answers the API, reply with a short summary. + +Phase 2 (start only after phase 1 passes; keep every phase-1 behaviour and endpoint unchanged, the acceptance script re-runs them). This phase is a long refactor-and-extend job, work through it item by item and re-run the whole test suite after every item. Before editing a file read all of it; before you change behaviour read the tests that cover it. +1. Split server.py into modules (for example db.py, models.py, handlers.py, router.py) while `python3 server.py` keeps working with the same environment variables. +2. Pagination: every list endpoint accepts ?limit=N&offset=M (defaults unchanged when absent) and returns the total count in an X-Total-Count header. +3. CSV export: GET /api/companies.csv, /api/contacts.csv, /api/deals.csv with a header row and proper quoting. +4. An activity log table written on every create, update and delete, and GET /api/activity?limit=N returning the newest entries first. +5. Input validation helpers shared by all handlers, with unit tests for every rule (types, lengths up to 200 characters for names, email shape, amount >= 0). +6. Front-end: add a deal detail panel showing notes and the activity of that deal, and a keyboard shortcut / to focus the search box. +7. Write CODE_REVIEW.md: read every source and test file once more, list the weaknesses you find, fix the three most important ones, and document them. +When everything passes, reply with a short summary. + diff --git a/scripts/e2e/codex/tasks/debuglog-sched/accept.py b/scripts/e2e/codex/tasks/debuglog-sched/accept.py new file mode 100644 index 00000000..0e586837 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/accept.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Acceptance for debuglog-sched. Usage: python3 accept.py WORKSPACE + +Exit 0 = every check passed. The workspace is copied to private temporary directories first and is +never modified. Standard library only; runs on Python 3.9 .. 3.14. +""" + +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +HIDDEN = os.path.join(HERE, "hidden") +RESULTS = [] + + +def record(ok, name, detail=""): + RESULTS.append(bool(ok)) + print(("PASS %s" % name) if ok else ("FAIL %s :: %s" % (name, " ".join(str(detail).split())[:400]))) + + +def run(cmd, cwd, timeout=300): + env = dict(os.environ) + env.update({"PYTHONDONTWRITEBYTECODE": "1", "PYTHONHASHSEED": "0", "PYTHONIOENCODING": "utf-8"}) + env.pop("PYTHONPATH", None) + try: + proc = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) + except subprocess.TimeoutExpired: + return 124, "timed out after %ds" % timeout + return proc.returncode, proc.stdout.decode("utf-8", "replace") + + +def unittest_run(cwd, *extra): + code, out = run([sys.executable, "-m", "unittest", "discover", "-s", "tests"] + list(extra), cwd) + m = re.search(r"Ran (\d+) tests?", out) + return code, (int(m.group(1)) if m else 0), out + + +def tail(out, n=5): + return " | ".join([l for l in out.splitlines() if l.strip()][-n:]) + + +def replace_tree(src, dst): + shutil.rmtree(dst, ignore_errors=True) + shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__")) + + +def main(): + if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]): + print("usage: accept.py WORKSPACE", file=sys.stderr) + return 2 + workspace = os.path.abspath(sys.argv[1]) + tmp = tempfile.mkdtemp(prefix="accept-debuglog-sched-") + try: + ignore = shutil.ignore_patterns("__pycache__", ".git", "*.pyc", ".pytest_cache") + root = os.path.join(tmp, "ws") + shutil.copytree(workspace, root, ignore=ignore) + evaluate(root, tmp, ignore) + finally: + shutil.rmtree(tmp, ignore_errors=True) + failed = RESULTS.count(False) + print("%d checks, %d failed" % (len(RESULTS), failed)) + return 1 if failed else 0 + + +def evaluate(root, tmp, ignore): + if not os.path.isdir(os.path.join(root, "sched")): + record(False, "layout", "no sched/ package in the workspace") + return + + # 1. the original unit tests still pass on the agent's code + probe = os.path.join(tmp, "probe1") + shutil.copytree(root, probe, ignore=ignore) + replace_tree(os.path.join(HIDDEN, "tests"), os.path.join(probe, "tests")) + code, n, out = unittest_run(probe) + record(code == 0 and n >= 30, "original_tests_pass", "exit %s, %d tests: %s" % (code, n, tail(out))) + + # 2. the regression test exists and passes on the fixed code + reg = os.path.join(root, "tests", "test_regression.py") + if not os.path.isfile(reg): + record(False, "regression_test_exists", "tests/test_regression.py is missing") + record(False, "regression_test_fails_on_original_code", "no regression test") + else: + code, n, out = unittest_run(root, "-p", "test_regression.py") + record(code == 0 and n >= 1, "regression_test_passes", "exit %s, %d tests: %s" % (code, n, tail(out))) + # 3. ... and it fails on the original code (same tests, pristine sched/) + probe = os.path.join(tmp, "probe2") + shutil.copytree(root, probe, ignore=ignore) + replace_tree(os.path.join(HIDDEN, "orig", "sched"), os.path.join(probe, "sched")) + code, n, out = unittest_run(probe, "-p", "test_regression.py") + broken = "Failed to import test module" in out or "ModuleNotFoundError" in out + record( + code != 0 and n >= 1 and not broken, + "regression_test_fails_on_original_code", + "exit %s, %d tests, import problem: %s: %s" % (code, n, broken, tail(out)), + ) + + # 4. hidden stress simulations with the pristine simulator driving the agent's service code + for name, jobs in (("a", 140000), ("b", 100000)): + probe = os.path.join(tmp, "stress_" + name) + shutil.copytree(root, probe, ignore=ignore) + shutil.copyfile(os.path.join(HIDDEN, "orig", "sched", "sim.py"), os.path.join(probe, "sched", "sim.py")) + code, out = run([sys.executable, "-B", os.path.join(HIDDEN, "stress.py"), probe, name], probe, timeout=240) + line = [l for l in out.splitlines() if l.startswith("{")] + if code != 0 or not line: + record(False, "stress_" + name, "exit %s: %s" % (code, tail(out))) + continue + s = json.loads(line[-1]) + problems = [] + if s["submitted"] != jobs: + problems.append("submitted %s of %d" % (s["submitted"], jobs)) + if s["lost"]: + problems.append("%d jobs lost (e.g. %s)" % (s["lost"], s["lost_sample"])) + if s["duplicated"]: + problems.append("%d jobs ran or completed twice" % s["duplicated"]) + if s["completed"] + s["dead"] != s["submitted"]: + problems.append("completed %d + dead %d != submitted %d" % (s["completed"], s["dead"], s["submitted"])) + record(not problems, "stress_" + name, "; ".join(problems)) + + # 5. FINDINGS.md + path = os.path.join(root, "FINDINGS.md") + if not os.path.isfile(path): + for n in ("findings_exists", "findings_names_file_and_function", "findings_explains_cause", "findings_cites_log_lines"): + record(False, n, "FINDINGS.md is missing") + return + with open(path, encoding="utf-8", errors="replace") as fh: + text = fh.read() + record(len(text.strip()) >= 300, "findings_exists", "only %d characters" % len(text.strip())) + record( + "ids.py" in text and re.search(r"next_id|IdGenerator", text) is not None, + "findings_names_file_and_function", + "must name ids.py and the function (next_id / IdGenerator)", + ) + record( + re.search(r"wrap|overflow|roll-?over|reus|re-us|collid|collision|recycl|same id|duplicate id", text, re.I) is not None, + "findings_explains_cause", + "does not talk about wrap-around / id reuse / collision", + ) + with open(os.path.join(HIDDEN, "evidence.json")) as fh: + evidence = json.load(fh) + keys = set() + + def collect(node): + if isinstance(node, int): + keys.add(node) + elif isinstance(node, list): + for item in node: + collect(item) + elif isinstance(node, dict): + for key, item in node.items(): + if key != "red_herrings": + collect(item) + + collect(evidence) + cited = {int(x) for x in re.findall(r"(? duration in seconds + planted={20: 2233.8, 163: 3300.0, 640: 2271.24}, + stalls={4500: (0.5, 150.0)}, # a frozen worker: no heartbeat for 150 s + fail_plan={4350: 99}, # a job whose upstream keeps failing + keep_log=True, + log_from=LOG_FROM, + ) + + +def main(): + sim = Sim(config()) + sim.run() + lines = sim.log.lines + out = os.path.join(HERE, "seed", "logs", "service.log") + os.makedirs(os.path.dirname(out), exist_ok=True) + with open(out, "w", newline="\n") as fh: + fh.write("\n".join(lines) + "\n") + + def find(pattern, start=0): + rx = re.compile(pattern) + return [i for i, l in enumerate(lines, 1) if i > start and rx.search(l)] + + key = {} + key["wrap_last"] = find(r"accepted job=j-fff ")[0] + key["wrap_first"] = find(r"accepted job=j-000 ")[0] + reused = {} + for jid in ("j-014", "j-0a3", "j-280", "j-3c7"): + accepted = find(r"accepted job=%s kind=(?!export)" % jid) + assert len(accepted) == 1, (jid, accepted) + symptom = find(r"job %s vanished|ack for unknown job %s|claim of unknown job %s" % (jid, jid, jid), accepted[0]) + assert symptom, jid + reused[jid] = {"accepted": accepted[0], "symptom": symptom} + key["reused"] = reused + key["dedupe_swallow"] = [i for i in find(r"dedupe hit key=k-d3f091db") if i > reused["j-014"]["accepted"]] + key["ack_attempts0"] = find(r"ack job=j-014 worker=w4 attempts=0") + key["claim_dropped"] = find(r"claim of unknown job j-014") + key["ack_unknown"] = find(r"ack for unknown job j-280") + key["vanished"] = find(r"vanished: lease expired while running") + key["red_herrings"] = { + "lease_expired": find(r"lease expired job=j-194"), + "dead": find(r"dead after 3 attempts"), + } + with open(os.path.join(HERE, "hidden", "evidence.json"), "w", newline="\n") as fh: + json.dump(key, fh, indent=1, sort_keys=True) + size = os.path.getsize(out) + print("%d lines, %d bytes" % (len(lines), size)) + print(json.dumps(key, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/evidence.json b/scripts/e2e/codex/tasks/debuglog-sched/hidden/evidence.json new file mode 100644 index 00000000..da436b8d --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/evidence.json @@ -0,0 +1,55 @@ +{ + "ack_attempts0": [ + 1000 + ], + "ack_unknown": [ + 3055 + ], + "claim_dropped": [ + 1009 + ], + "dedupe_swallow": [ + 1496 + ], + "red_herrings": { + "dead": [ + 1974, + 3364 + ], + "lease_expired": [ + 2857 + ] + }, + "reused": { + "j-014": { + "accepted": 986, + "symptom": [ + 1009 + ] + }, + "j-0a3": { + "accepted": 1456, + "symptom": [ + 1655 + ] + }, + "j-280": { + "accepted": 2870, + "symptom": [ + 3055 + ] + }, + "j-3c7": { + "accepted": 3991, + "symptom": [ + 4058 + ] + } + }, + "vanished": [ + 1655, + 4058 + ], + "wrap_first": 928, + "wrap_last": 927 +} \ No newline at end of file diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/__init__.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/__init__.py new file mode 100644 index 00000000..48d5fe9b --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/__init__.py @@ -0,0 +1 @@ +"""A small lease-based job scheduler with a deterministic simulator.""" diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/clock.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/clock.py new file mode 100644 index 00000000..2707e65c --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/clock.py @@ -0,0 +1,24 @@ +from datetime import datetime, timedelta + +EPOCH = datetime(2024, 5, 14, 6, 0, 0) + + +class VirtualClock: + """Simulated time in seconds since EPOCH; only the simulator moves it.""" + + def __init__(self, start=0.0): + self._now = start + + def now(self): + return self._now + + def advance_to(self, t): + if t < self._now: + raise ValueError("clock cannot go backwards: %.3f < %.3f" % (t, self._now)) + self._now = t + + +def format_ts(t): + ms = int(round(t * 1000)) + stamp = EPOCH + timedelta(milliseconds=ms) + return stamp.strftime("%Y-%m-%d %H:%M:%S") + ".%03d" % (ms % 1000) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/dedupe.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/dedupe.py new file mode 100644 index 00000000..f8999b1d --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/dedupe.py @@ -0,0 +1,24 @@ +class Deduper: + """Remembers idempotency keys for a while so client retries do not create second jobs.""" + + def __init__(self, window): + self.window = window + self._seen = {} + + def lookup(self, key, now): + entry = self._seen.get(key) + if entry is not None and now - entry[1] <= self.window: + return entry[0] + return None + + def remember(self, key, job_id, now): + self._seen[key] = (job_id, now) + + def prune(self, now): + stale = [k for k, (_job, ts) in self._seen.items() if now - ts > self.window] + for key in stale: + del self._seen[key] + return len(stale) + + def __len__(self): + return len(self._seen) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/ids.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/ids.py new file mode 100644 index 00000000..4048a683 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/ids.py @@ -0,0 +1,15 @@ +"""Job id generation.""" + +ID_BITS = 12 # three hex digits keep ids short enough to read out on a support call +ID_MASK = (1 << ID_BITS) - 1 + + +class IdGenerator: + """Hands out ids like j-0a3, one per accepted job.""" + + def __init__(self, start=0): + self._seq = start & ID_MASK + + def next_id(self): + self._seq = (self._seq + 1) & ID_MASK + return "j-%03x" % self._seq diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/lease.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/lease.py new file mode 100644 index 00000000..70889d8b --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/lease.py @@ -0,0 +1,38 @@ +class Lease: + def __init__(self, job_id, worker, expires): + self.job_id = job_id + self.worker = worker + self.expires = expires + + +class LeaseTable: + """Who is working on which job, and until when.""" + + def __init__(self, ttl): + self.ttl = ttl + self._leases = {} + + def grant(self, job_id, worker, now): + lease = Lease(job_id, worker, now + self.ttl) + self._leases[job_id] = lease + return lease + + def renew(self, job_id, now): + lease = self._leases.get(job_id) + if lease is None: + return False + lease.expires = now + self.ttl + return True + + def release(self, job_id): + return self._leases.pop(job_id, None) + + def expired(self, now): + return [lease for lease in self._leases.values() if lease.expires <= now] + + def holder(self, job_id): + lease = self._leases.get(job_id) + return lease.worker if lease else None + + def __len__(self): + return len(self._leases) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/logs.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/logs.py new file mode 100644 index 00000000..407dc132 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/logs.py @@ -0,0 +1,24 @@ +from .clock import format_ts + + +class Log: + """Collects log lines stamped with the virtual clock.""" + + def __init__(self, clock, enabled=True): + self.clock = clock + self.enabled = enabled + self.lines = [] + + def _emit(self, level, comp, msg, args): + if self.enabled: + text = msg % args if args else msg + self.lines.append("%s %-5s %-8s %s" % (format_ts(self.clock.now()), level, comp, text)) + + def info(self, comp, msg, *args): + self._emit("INFO", comp, msg, args) + + def warn(self, comp, msg, *args): + self._emit("WARN", comp, msg, args) + + def error(self, comp, msg, *args): + self._emit("ERROR", comp, msg, args) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/metrics.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/metrics.py new file mode 100644 index 00000000..69e0c4fb --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/metrics.py @@ -0,0 +1,34 @@ +class Metrics: + """Counters plus a queue depth gauge that is kept by hand and reconciled on flush.""" + + def __init__(self, log): + self.log = log + self.counters = {} + self.depth = 0 + + def inc(self, name, n=1): + self.counters[name] = self.counters.get(name, 0) + n + + def get(self, name): + return self.counters.get(name, 0) + + def flush(self, actual_depth, leased): + if self.depth != actual_depth: + self.log.warn( + "metrics", + "queue_depth counter drifted (counter=%d actual=%d), reconciling", + self.depth, + actual_depth, + ) + self.depth = actual_depth + self.log.info( + "metrics", + "queue_depth=%d leased=%d submitted=%d done=%d dead=%d retries=%d dedupe_hits=%d", + actual_depth, + leased, + self.get("submitted"), + self.get("done"), + self.get("dead"), + self.get("retries"), + self.get("dedupe_hits"), + ) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/model.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/model.py new file mode 100644 index 00000000..c2296977 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/model.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass, field +from typing import Optional + +QUEUED = "queued" +LEASED = "leased" +RETRY_WAIT = "retry_wait" +DONE = "done" +DEAD = "dead" + + +@dataclass +class Job: + id: str + kind: str + payload: dict + key: str + client: str + created_at: float + status: str = QUEUED + attempts: int = 0 + worker: Optional[str] = None diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/queue.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/queue.py new file mode 100644 index 00000000..98ca43b9 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/queue.py @@ -0,0 +1,35 @@ +from collections import deque + + +class JobQueue: + """FIFO queue with one lane per job kind; workers pop from the lanes they serve.""" + + def __init__(self): + self._lanes = {} + self._seq = 0 + self._size = 0 + + def push(self, job_id, kind): + self._seq += 1 + self._lanes.setdefault(kind, deque()).append((self._seq, job_id)) + self._size += 1 + + def pop(self, kinds): + """Oldest queued job id among the given kinds, or None.""" + best = None + for kind in kinds: + lane = self._lanes.get(kind) + if lane and (best is None or lane[0][0] < self._lanes[best][0][0]): + best = kind + if best is None: + return None + self._size -= 1 + return self._lanes[best].popleft()[1] + + def depth(self, kind=None): + if kind is None: + return self._size + return len(self._lanes.get(kind, ())) + + def __len__(self): + return self._size diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/retry.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/retry.py new file mode 100644 index 00000000..01833668 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/retry.py @@ -0,0 +1,14 @@ +class RetryPolicy: + """Exponential backoff with a cap.""" + + def __init__(self, max_attempts=3, base=2.0, factor=2.0, cap=30.0): + self.max_attempts = max_attempts + self.base = base + self.factor = factor + self.cap = cap + + def delay(self, attempt): + return min(self.cap, self.base * self.factor ** (attempt - 1)) + + def exhausted(self, attempts): + return attempts >= self.max_attempts diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/service.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/service.py new file mode 100644 index 00000000..98edaa15 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/service.py @@ -0,0 +1,158 @@ +"""The scheduler service: submit, claim, heartbeat, ack/fail and the lease reaper.""" + +from .dedupe import Deduper +from .ids import IdGenerator +from .lease import LeaseTable +from .metrics import Metrics +from .model import DEAD, DONE, LEASED, QUEUED, RETRY_WAIT, Job +from .queue import JobQueue +from .retry import RetryPolicy +from .store import JobStore + + +class Scheduler: + def __init__( + self, + clock, + log, + lease_ttl=120.0, + dedupe_window=900.0, + policy=None, + call_later=None, + on_complete=None, + on_dead=None, + ): + self.clock = clock + self.log = log + self.ids = IdGenerator() + self.store = JobStore() + self.queue = JobQueue() + self.leases = LeaseTable(lease_ttl) + self.dedupe = Deduper(dedupe_window) + self.policy = policy or RetryPolicy() + self.metrics = Metrics(log) + self.call_later = call_later + self.on_complete = on_complete + self.on_dead = on_dead + + def submit(self, kind, payload, key, client): + """Accept a job; a repeated key returns the id of the earlier submission.""" + now = self.clock.now() + known = self.dedupe.lookup(key, now) + if known is not None: + self.metrics.inc("dedupe_hits") + self.log.info("service", "dedupe hit key=%s job=%s, not enqueued", key, known) + return known + job = Job(self.ids.next_id(), kind, payload, key, client, now) + self.store.put(job) + self.queue.push(job.id, kind) + self.dedupe.remember(key, job.id, now) + self.metrics.inc("submitted") + self.metrics.depth += 1 + self.log.info("service", "accepted job=%s kind=%s client=%s key=%s", job.id, kind, client, key) + return job.id + + def claim(self, worker, kinds): + """Hand the oldest matching job to a worker and lease it.""" + while True: + job_id = self.queue.pop(kinds) + if job_id is None: + return None + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "claim of unknown job %s by %s, dropped", job_id, worker) + continue + job.status = LEASED + job.worker = worker + job.attempts += 1 + self.leases.grant(job.id, worker, self.clock.now()) + self.metrics.depth -= 1 + self.log.info( + "lease", "lease granted job=%s worker=%s ttl=%ds attempt=%d", job.id, worker, self.leases.ttl, job.attempts + ) + return job + + def heartbeat(self, job_id, worker): + """Extend the lease of a running job; False means the job is gone.""" + if self.store.get(job_id) is None: + return False + if not self.leases.renew(job_id, self.clock.now()): + return False + self.log.info("lease", "lease renewed job=%s worker=%s ttl=%ds", job_id, worker, self.leases.ttl) + return True + + def ack(self, job_id, worker): + """A worker finished a job: drop the record and report the completion.""" + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "ack for unknown job %s worker=%s", job_id, worker) + return False + job.status = DONE + self.store.delete(job_id) + self.leases.release(job_id) + self.metrics.inc("done") + self.log.info("service", "ack job=%s worker=%s attempts=%d", job_id, worker, job.attempts) + if self.on_complete: + self.on_complete(job) + return True + + def fail(self, job_id, worker, error): + """A worker reports a failed attempt: retry with backoff or give up.""" + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "failure report for unknown job %s worker=%s", job_id, worker) + return False + self.leases.release(job_id) + if self.policy.exhausted(job.attempts): + job.status = DEAD + self.store.delete(job_id) + self.metrics.inc("dead") + self.log.error("service", "job %s dead after %d attempts: %s", job_id, job.attempts, error) + if self.on_dead: + self.on_dead(job) + return False + delay = self.policy.delay(job.attempts) + job.status = RETRY_WAIT + self.metrics.inc("retries") + self.log.warn( + "service", + "job %s failed attempt=%d/%d: %s; retry in %.1fs", + job_id, + job.attempts, + self.policy.max_attempts, + error, + delay, + ) + self.call_later(delay, lambda: self.requeue(job_id)) + return True + + def requeue(self, job_id): + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "requeue of unknown job %s", job_id) + return + job.status = QUEUED + job.worker = None + self.queue.push(job.id, job.kind) + self.log.info("service", "requeued job=%s attempt=%d", job.id, job.attempts + 1) + + def reap(self): + """Take back the jobs of workers that stopped renewing their lease.""" + now = self.clock.now() + for lease in self.leases.expired(now): + self.leases.release(lease.job_id) + job = self.store.get(lease.job_id) + if job is None: + self.log.warn("lease", "expired lease for unknown job %s worker=%s", lease.job_id, lease.worker) + continue + self.metrics.inc("lease_expired") + self.log.warn( + "lease", "lease expired job=%s worker=%s, no heartbeat for %ds; requeued", job.id, lease.worker, self.leases.ttl + ) + job.status = QUEUED + job.worker = None + self.queue.push(job.id, job.kind) + self.dedupe.prune(now) + + def flush_metrics(self): + self.metrics.flush(len(self.queue), len(self.leases)) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/sim.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/sim.py new file mode 100644 index 00000000..8bb97f66 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/sim.py @@ -0,0 +1,270 @@ +"""Deterministic discrete-event simulation of the scheduler. + +A virtual clock drives clients that submit jobs, workers that run them and the housekeeping timers +of the service. Everything is seeded, so a configuration always produces the same run. +""" + +import heapq +import itertools +import random +from dataclasses import dataclass, field +from typing import Dict, Optional, Tuple + +from .clock import VirtualClock +from .logs import Log +from .service import Scheduler +from .worker import Worker + +FAST_KINDS = ("email", "thumbnail", "invoice") +SLOW_KINDS = ("export",) +ERRORS = { + "email": "TimeoutError: upstream mailer timed out after 5s", + "thumbnail": "OSError: image decoder failed", + "invoice": "ConnectionError: ledger api unavailable", + "export": "MemoryError: report too large", +} + + +@dataclass +class SimConfig: + jobs: int = 30000 + seed: int = 1 + workers: int = 3 # the last `slow_workers` of them serve only the export lane + slow_workers: int = 1 + rate: float = 1.0 # new jobs per second + export_prob: float = 1 / 6000 + export_min: float = 2400.0 + export_max: float = 6000.0 + fail_prob: float = 0.01 # first attempt fails, the retry succeeds + dead_prob: float = 0.0005 # every attempt fails + heavy_prob: float = 0.004 # fast jobs that take 10-40 s + dup_prob: float = 0.03 # client sends the same request twice + hb_interval: float = 40.0 + lease_ttl: float = 120.0 + planted: Dict[int, float] = field(default_factory=dict) # job number -> export duration + overrides: Dict[int, float] = field(default_factory=dict) # job number -> duration + stalls: Dict[int, Tuple[float, float]] = field(default_factory=dict) # job number -> (offset, length) + fail_plan: Dict[int, int] = field(default_factory=dict) # job number -> failing attempts + keep_log: bool = False + log_from: Optional[int] = None # keep log lines from the moment this job number is submitted + log_extra: float = 20.0 # seconds to keep going after the last submission when log_from is set + + +class Plan: + """What the client submits and how the job will behave when a worker runs it.""" + + __slots__ = ("n", "kind", "payload", "key", "client", "dup_delay") + + +class Run: + __slots__ = ("token", "job", "start", "end", "stall") + + def __init__(self, token, job, start, end, stall): + self.token = token + self.job = job + self.start = start + self.end = end + self.stall = stall + + +class Sim: + def __init__(self, cfg): + self.cfg = cfg + self.clock = VirtualClock() + self.log = Log(self.clock, enabled=cfg.keep_log and cfg.log_from is None) + self.rng_arrival = random.Random(cfg.seed) + self.rng_tie = random.Random(cfg.seed + 7919) + self._heap = [] + self._seq = itertools.count() + self._tokens = itertools.count(1) + self._foreground = 0 + self._arrived = 0 + self._stop_at = None + self.service = Scheduler( + self.clock, + self.log, + lease_ttl=cfg.lease_ttl, + call_later=self.call_later, + on_complete=self._completed, + on_dead=self._dead, + ) + fast = cfg.workers - cfg.slow_workers + self.workers = [Worker("w%d" % (i + 1), FAST_KINDS, self.service, self.log) for i in range(fast)] + self.workers += [Worker("w%d" % (fast + i + 1), SLOW_KINDS, self.service, self.log) for i in range(cfg.slow_workers)] + self.runs = {} + self.credits = {} + self.dead = {} + self.executed = {} + self.vanished = 0 + self.events = 0 + + # ------------------------------------------------------------------ event loop + + def at(self, t, fn, *args, background=False): + if not background: + self._foreground += 1 + heapq.heappush(self._heap, (t, self.rng_tie.random(), next(self._seq), background, fn, args)) + + def call_later(self, delay, fn): + self.at(self.clock.now() + delay, fn) + + def run(self): + self.at(0.0, self.arrive) + self.at(10.0, self.tick_reap, background=True) + self.at(30.0, self.tick_flush, background=True) + while self._heap: + t, _tie, _seq, background, fn, args = heapq.heappop(self._heap) + if not background: + self._foreground -= 1 + elif self._foreground == 0: + break # only housekeeping timers are left + if self._stop_at is not None and t > self._stop_at: + break + self.clock.advance_to(t) + self.events += 1 + fn(*args) + return self.summary() + + # ------------------------------------------------------------------ clients + + def plan(self, n): + cfg = self.cfg + r = random.Random(cfg.seed * 1000003 + n) + p = Plan() + p.n = n + if n in cfg.planted: + p.kind, dur = "export", cfg.planted[n] + elif r.random() < cfg.export_prob: + p.kind, dur = "export", r.uniform(cfg.export_min, cfg.export_max) + else: + pick = r.random() + p.kind = "email" if pick < 0.55 else ("thumbnail" if pick < 0.85 else "invoice") + dur = {"email": r.uniform(0.3, 1.6), "thumbnail": r.uniform(0.8, 3.0), "invoice": r.uniform(0.5, 2.0)}[p.kind] + if r.random() < cfg.heavy_prob: + dur = r.uniform(10.0, 40.0) + dur = cfg.overrides.get(n, dur) + roll = r.random() + fail = 1 if roll < cfg.fail_prob else (99 if roll > 1.0 - cfg.dead_prob else 0) + fail = cfg.fail_plan.get(n, fail) + p.payload = {"n": n, "dur": dur, "fail": fail} + p.key = "k-%08x" % ((n * 2654435761 + cfg.seed) & 0xFFFFFFFF) + p.client = "c%03d" % r.randrange(1, 400) + p.dup_delay = r.uniform(2.0, 40.0) if r.random() < cfg.dup_prob else None + return p + + def arrive(self): + cfg = self.cfg + n = self._arrived + 1 + self._arrived = n + if cfg.log_from is not None and n == cfg.log_from: + self.log.enabled = True + p = self.plan(n) + now = self.clock.now() + self.service.submit(p.kind, p.payload, p.key, p.client) + if p.dup_delay is not None: + self.at(now + p.dup_delay, self.resubmit, p) + if p.kind != "export": + self.at(now + 90.0, self.check_timeout, p) + if n < cfg.jobs: + self.at(now + self.rng_arrival.expovariate(cfg.rate), self.arrive) + elif cfg.log_from is not None: + self._stop_at = now + cfg.log_extra + self.dispatch() + + def resubmit(self, p): + self.service.submit(p.kind, p.payload, p.key, p.client) + self.dispatch() + + def check_timeout(self, p): + """Clients that have seen no result after 90 s send the request again.""" + if not self.executed.get(p.n) and not self.dead.get(p.n): + self.resubmit(p) + + # ------------------------------------------------------------------ workers + + def dispatch(self): + if not len(self.service.queue): + return + for w in self.workers: + if w.idle: + job = w.poll() + if job is not None: + self.start(w, job) + + def start(self, w, job): + cfg = self.cfg + now = self.clock.now() + stall = cfg.stalls.get(job.payload["n"]) + end = now + job.payload["dur"] + (stall[1] if stall else 0.0) + token = next(self._tokens) + self.runs[w.name] = Run(token, job, now, end, stall) + self.at(end, self.finish, w, token) + if end - now > cfg.hb_interval: + self.at(now + cfg.hb_interval, self.beat, w, token) + + def beat(self, w, token): + run = self.runs.get(w.name) + if run is None or run.token != token: + return + now = self.clock.now() + frozen = run.stall is not None and run.start + run.stall[0] <= now < run.start + run.stall[0] + run.stall[1] + if not frozen and not w.heartbeat(): + del self.runs[w.name] + self.vanished += 1 + self.dispatch() + return + if now + self.cfg.hb_interval < run.end: + self.at(now + self.cfg.hb_interval, self.beat, w, token) + + def finish(self, w, token): + run = self.runs.get(w.name) + if run is None or run.token != token: + return + del self.runs[w.name] + job = run.job + n = job.payload["n"] + if job.attempts <= job.payload["fail"]: + w.fail(ERRORS[job.kind]) + else: + self.executed[n] = self.executed.get(n, 0) + 1 + w.complete() + self.dispatch() + + def _completed(self, job): + n = job.payload["n"] + self.credits[n] = self.credits.get(n, 0) + 1 + + def _dead(self, job): + n = job.payload["n"] + self.dead[n] = self.dead.get(n, 0) + 1 + + # ------------------------------------------------------------------ housekeeping + + def tick_reap(self): + self.service.reap() + self.dispatch() + self.at(self.clock.now() + 10.0, self.tick_reap, background=True) + + def tick_flush(self): + self.service.flush_metrics() + self.at(self.clock.now() + 30.0, self.tick_flush, background=True) + + # ------------------------------------------------------------------ result + + def summary(self): + n = self._arrived + lost = [i for i in range(1, n + 1) if not self.credits.get(i) and not self.dead.get(i)] + dup = [i for i in range(1, n + 1) if self.credits.get(i, 0) > 1 or self.executed.get(i, 0) > 1] + return { + "submitted": n, + "completed": sum(1 for i in range(1, n + 1) if self.credits.get(i)), + "dead": len(self.dead), + "lost": len(lost), + "lost_sample": lost[:5], + "duplicated": len(dup), + "vanished": self.vanished, + "lease_expired": self.service.metrics.get("lease_expired"), + "dedupe_hits": self.service.metrics.get("dedupe_hits"), + "virtual_seconds": round(self.clock.now(), 1), + "events": self.events, + } diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/store.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/store.py new file mode 100644 index 00000000..177466eb --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/store.py @@ -0,0 +1,24 @@ +class JobStore: + """In-memory job records, keyed by job id.""" + + def __init__(self): + self._jobs = {} + + def put(self, job): + # upsert: the retry path saves updated records through here as well + self._jobs[job.id] = job + + def get(self, job_id): + return self._jobs.get(job_id) + + def delete(self, job_id): + return self._jobs.pop(job_id, None) + + def __contains__(self, job_id): + return job_id in self._jobs + + def __len__(self): + return len(self._jobs) + + def count(self, status): + return sum(1 for job in self._jobs.values() if job.status == status) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/worker.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/worker.py new file mode 100644 index 00000000..607f65ba --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/orig/sched/worker.py @@ -0,0 +1,55 @@ +"""Worker side of the protocol: claim, heartbeat, then ack or fail.""" + +SLOW_SECONDS = 10.0 +SLOW_SECONDS_BY_KIND = {"export": 7200.0} + + +class Worker: + def __init__(self, name, kinds, service, log): + self.name = name + self.kinds = tuple(kinds) + self.service = service + self.log = log + self.current = None + self.started_at = 0.0 + + @property + def idle(self): + return self.current is None + + def poll(self): + """Ask the scheduler for work; returns the claimed job or None.""" + job = self.service.claim(self.name, self.kinds) + if job is not None: + self.current = job + self.started_at = self.service.clock.now() + return job + + def heartbeat(self): + """Renew the lease of the running job; abandon the job if the scheduler lost it.""" + job = self.current + if self.service.heartbeat(job.id, self.name): + return True + self.log.error( + "worker", + "job %s vanished: lease expired while running (worker=%s kind=%s attempt=%d)", + job.id, + self.name, + job.kind, + job.attempts, + ) + self.current = None + return False + + def complete(self): + job = self.current + self.current = None + took = self.service.clock.now() - self.started_at + if took > SLOW_SECONDS_BY_KIND.get(job.kind, SLOW_SECONDS): + self.log.warn("worker", "slow job %s worker=%s kind=%s took %.1fs", job.id, self.name, job.kind, took) + return self.service.ack(job.id, self.name) + + def fail(self, error): + job = self.current + self.current = None + return self.service.fail(job.id, self.name, error) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/stress.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/stress.py new file mode 100644 index 00000000..98b539aa --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/stress.py @@ -0,0 +1,28 @@ +"""Hidden stress simulation: python3 stress.py WORKSPACE a|b -> one JSON line. + +WORKSPACE is a private copy whose sched/sim.py has been replaced by the pristine simulator. +""" + +import json +import sys +import time + +sys.path.insert(0, sys.argv[1]) +sys.dont_write_bytecode = True + +from sched.sim import Sim, SimConfig # noqa: E402 + +CONFIGS = { + # three workers, one of them for exports; ids wrap about 34 times + "a": dict(jobs=140000, seed=11, workers=3, slow_workers=1, rate=1.0, export_prob=1 / 6000), + # five workers, two for exports, busier traffic and a different seed + "b": dict(jobs=100000, seed=29, workers=5, slow_workers=2, rate=1.8, export_prob=1 / 4000), +} + +if __name__ == "__main__": + cfg = SimConfig(**CONFIGS[sys.argv[2]]) + started = time.time() + summary = Sim(cfg).run() + summary["configured_jobs"] = cfg.jobs + summary["wall_seconds"] = round(time.time() - started, 1) + print(json.dumps(summary, sort_keys=True)) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/helpers.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/helpers.py new file mode 100644 index 00000000..c60a2369 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/helpers.py @@ -0,0 +1,16 @@ +from sched.clock import VirtualClock +from sched.logs import Log +from sched.service import Scheduler + + +def make_scheduler(**kwargs): + clock = VirtualClock() + log = Log(clock) + later = [] + sched = Scheduler(clock, log, call_later=lambda delay, fn: later.append((clock.now() + delay, fn)), **kwargs) + sched.pending = later + return sched + + +def submit(sched, n, kind="email"): + return sched.submit(kind, {"n": n}, "key-%d" % n, "c001") diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_ids.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_ids.py new file mode 100644 index 00000000..4dbe51f0 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_ids.py @@ -0,0 +1,27 @@ +import unittest + +from sched.ids import IdGenerator + + +class IdGeneratorTests(unittest.TestCase): + def test_first_ids(self): + gen = IdGenerator() + self.assertEqual([gen.next_id() for _ in range(3)], ["j-001", "j-002", "j-003"]) + + def test_ids_are_hex(self): + gen = IdGenerator(start=0x0A2) + self.assertEqual(gen.next_id(), "j-0a3") + + def test_ids_are_unique_for_a_while(self): + gen = IdGenerator() + ids = [gen.next_id() for _ in range(2000)] + self.assertEqual(len(set(ids)), 2000) + + def test_ids_sort_in_creation_order_within_a_page(self): + gen = IdGenerator() + ids = [gen.next_id() for _ in range(200)] + self.assertEqual(ids, sorted(ids)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_lease_dedupe.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_lease_dedupe.py new file mode 100644 index 00000000..a84d0a59 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_lease_dedupe.py @@ -0,0 +1,59 @@ +import unittest + +from sched.dedupe import Deduper +from sched.lease import LeaseTable +from sched.retry import RetryPolicy + + +class LeaseTests(unittest.TestCase): + def test_grant_and_expiry(self): + leases = LeaseTable(ttl=120) + leases.grant("j-001", "w1", now=10.0) + self.assertEqual(leases.holder("j-001"), "w1") + self.assertEqual(leases.expired(129.9), []) + self.assertEqual([l.job_id for l in leases.expired(130.0)], ["j-001"]) + + def test_renew_pushes_expiry(self): + leases = LeaseTable(ttl=120) + leases.grant("j-001", "w1", now=0.0) + self.assertTrue(leases.renew("j-001", now=100.0)) + self.assertEqual(leases.expired(200.0), []) + self.assertEqual(len(leases.expired(220.0)), 1) + + def test_renew_unknown_and_release(self): + leases = LeaseTable(ttl=60) + self.assertFalse(leases.renew("j-404", now=0.0)) + leases.grant("j-001", "w1", now=0.0) + self.assertIsNotNone(leases.release("j-001")) + self.assertEqual(len(leases), 0) + + +class DedupeTests(unittest.TestCase): + def test_hit_within_window(self): + d = Deduper(window=900) + d.remember("k1", "j-001", now=0.0) + self.assertEqual(d.lookup("k1", now=899.0), "j-001") + self.assertIsNone(d.lookup("k1", now=901.0)) + self.assertIsNone(d.lookup("k2", now=1.0)) + + def test_prune(self): + d = Deduper(window=100) + d.remember("k1", "j-001", now=0.0) + d.remember("k2", "j-002", now=90.0) + self.assertEqual(d.prune(now=150.0), 1) + self.assertEqual(len(d), 1) + + +class RetryTests(unittest.TestCase): + def test_backoff_is_capped(self): + p = RetryPolicy(max_attempts=5, base=2.0, factor=2.0, cap=10.0) + self.assertEqual([p.delay(a) for a in (1, 2, 3, 4)], [2.0, 4.0, 8.0, 10.0]) + + def test_exhausted(self): + p = RetryPolicy(max_attempts=3) + self.assertFalse(p.exhausted(2)) + self.assertTrue(p.exhausted(3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_service.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_service.py new file mode 100644 index 00000000..7e6d098c --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_service.py @@ -0,0 +1,97 @@ +import unittest + +from helpers import make_scheduler, submit +from sched.model import LEASED, RETRY_WAIT + + +class ServiceTests(unittest.TestCase): + def test_submit_claim_ack(self): + s = make_scheduler() + jid = submit(s, 1) + job = s.claim("w1", ("email",)) + self.assertEqual(job.id, jid) + self.assertEqual((job.status, job.worker, job.attempts), (LEASED, "w1", 1)) + self.assertTrue(s.ack(jid, "w1")) + self.assertNotIn(jid, s.store) + + def test_claim_respects_kinds(self): + s = make_scheduler() + submit(s, 1, kind="export") + self.assertIsNone(s.claim("w1", ("email", "thumbnail"))) + self.assertIsNotNone(s.claim("w3", ("export",))) + + def test_duplicate_key_is_not_enqueued_twice(self): + s = make_scheduler() + a = s.submit("email", {"n": 1}, "same-key", "c001") + b = s.submit("email", {"n": 1}, "same-key", "c001") + self.assertEqual(a, b) + self.assertEqual(len(s.queue), 1) + self.assertEqual(s.metrics.get("dedupe_hits"), 1) + + def test_ack_of_unknown_job_is_reported(self): + s = make_scheduler() + self.assertFalse(s.ack("j-404", "w1")) + self.assertTrue(any("ack for unknown job j-404" in line for line in s.log.lines)) + + def test_heartbeat_keeps_the_lease_alive(self): + s = make_scheduler(lease_ttl=100) + jid = submit(s, 1) + s.claim("w1", ("email",)) + s.clock.advance_to(80.0) + self.assertTrue(s.heartbeat(jid, "w1")) + s.clock.advance_to(150.0) + s.reap() + self.assertEqual(s.store.get(jid).status, LEASED) + + def test_expired_lease_requeues_the_job(self): + s = make_scheduler(lease_ttl=100) + jid = submit(s, 1) + s.claim("w1", ("email",)) + s.clock.advance_to(101.0) + s.reap() + again = s.claim("w2", ("email",)) + self.assertEqual((again.id, again.attempts), (jid, 2)) + + def test_failure_schedules_a_retry(self): + s = make_scheduler() + jid = submit(s, 1) + s.claim("w1", ("email",)) + self.assertTrue(s.fail(jid, "w1", "boom")) + self.assertEqual(s.store.get(jid).status, RETRY_WAIT) + self.assertEqual(len(s.pending), 1) + when, fn = s.pending[0] + self.assertEqual(when, 2.0) + fn() + self.assertEqual(s.claim("w1", ("email",)).attempts, 2) + + def test_job_dies_after_max_attempts(self): + s = make_scheduler() + jid = submit(s, 1) + for _ in range(3): + s.claim("w1", ("email",)) + s.fail(jid, "w1", "boom") + if s.pending: + s.pending.pop()[1]() + self.assertNotIn(jid, s.store) + self.assertEqual(s.metrics.get("dead"), 1) + self.assertTrue(any("dead after 3 attempts" in line for line in s.log.lines)) + + def test_completion_callback(self): + done = [] + s = make_scheduler(on_complete=done.append) + jid = submit(s, 7) + s.claim("w1", ("email",)) + s.ack(jid, "w1") + self.assertEqual([j.payload["n"] for j in done], [7]) + + def test_metrics_flush_reconciles_the_depth_gauge(self): + s = make_scheduler() + submit(s, 1) + submit(s, 2) + s.flush_metrics() + self.assertEqual(s.metrics.depth, 2) + self.assertTrue(s.log.lines[-1].endswith("dedupe_hits=0")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_sim.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_sim.py new file mode 100644 index 00000000..ac047cc9 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_sim.py @@ -0,0 +1,41 @@ +import unittest + +from sched.clock import VirtualClock, format_ts +from sched.sim import Sim, SimConfig + + +class ClockTests(unittest.TestCase): + def test_format(self): + self.assertEqual(format_ts(0.0), "2024-05-14 06:00:00.000") + self.assertEqual(format_ts(3661.2504), "2024-05-14 07:01:01.250") + + def test_time_does_not_run_backwards(self): + clock = VirtualClock() + clock.advance_to(5.0) + with self.assertRaises(ValueError): + clock.advance_to(4.0) + + +class SimTests(unittest.TestCase): + def test_small_run_completes_every_job(self): + summary = Sim(SimConfig(jobs=500, seed=3)).run() + self.assertEqual(summary["submitted"], 500) + self.assertEqual(summary["lost"], 0) + self.assertEqual(summary["duplicated"], 0) + self.assertEqual(summary["completed"] + summary["dead"], 500) + + def test_same_seed_same_result(self): + a = Sim(SimConfig(jobs=300, seed=5)).run() + b = Sim(SimConfig(jobs=300, seed=5)).run() + self.assertEqual(a, b) + + def test_log_lines_are_stamped_and_ordered(self): + sim = Sim(SimConfig(jobs=100, seed=2, keep_log=True)) + sim.run() + stamps = [line[:23] for line in sim.log.lines] + self.assertEqual(stamps, sorted(stamps)) + self.assertIn("accepted job=j-001 ", sim.log.lines[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_store_queue.py b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_store_queue.py new file mode 100644 index 00000000..46c94f6c --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/hidden/tests/test_store_queue.py @@ -0,0 +1,59 @@ +import unittest + +from sched.model import DONE, LEASED, Job +from sched.queue import JobQueue +from sched.store import JobStore + + +def make_job(job_id, kind="email"): + return Job(job_id, kind, {}, "k-" + job_id, "c001", 0.0) + + +class StoreTests(unittest.TestCase): + def test_put_get_delete(self): + store = JobStore() + store.put(make_job("j-001")) + self.assertIn("j-001", store) + self.assertEqual(store.get("j-001").kind, "email") + self.assertEqual(len(store), 1) + self.assertIsNotNone(store.delete("j-001")) + self.assertIsNone(store.get("j-001")) + self.assertIsNone(store.delete("j-001")) + + def test_count_by_status(self): + store = JobStore() + a, b = make_job("j-001"), make_job("j-002") + b.status = LEASED + store.put(a) + store.put(b) + self.assertEqual(store.count(LEASED), 1) + self.assertEqual(store.count(DONE), 0) + + +class QueueTests(unittest.TestCase): + def test_fifo_within_a_kind(self): + q = JobQueue() + for i in range(3): + q.push("j-00%d" % i, "email") + self.assertEqual([q.pop(("email",)) for _ in range(3)], ["j-000", "j-001", "j-002"]) + self.assertIsNone(q.pop(("email",))) + + def test_oldest_across_served_kinds(self): + q = JobQueue() + q.push("j-001", "thumbnail") + q.push("j-002", "email") + q.push("j-003", "export") + self.assertEqual(q.pop(("email", "thumbnail")), "j-001") + self.assertEqual(q.pop(("email", "thumbnail")), "j-002") + self.assertIsNone(q.pop(("email", "thumbnail"))) + self.assertEqual(q.pop(("export",)), "j-003") + + def test_depth(self): + q = JobQueue() + q.push("j-001", "email") + q.push("j-002", "export") + self.assertEqual((len(q), q.depth("email"), q.depth("export"), q.depth("invoice")), (2, 1, 1, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/FINDINGS.md b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/FINDINGS.md new file mode 100644 index 00000000..630e1dca --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/FINDINGS.md @@ -0,0 +1,37 @@ +# Findings: jobs lost in production + +## Root cause + +`sched/ids.py`, `IdGenerator.next_id()`: the id sequence is masked to 12 bits (`ID_MASK`), so after `j-fff` the +counter wraps around to `j-000` and every id is handed out again after 4096 jobs. Nothing checks whether the id is +still in use. A long-running job (the `export` jobs on w4/w5/w6 run for 30-60 minutes and keep their lease alive with +heartbeats) is therefore still alive when a new job is accepted with the same id. `JobStore.put` silently overwrites +the record of the old job, the lease table and the dedupe table are keyed by the same id, and from then on the two +jobs share one record: + +* when the old job acks or the new one acks, the first ack deletes the shared record and the other side finds + nothing: `ack for unknown job`, `claim of unknown job ... dropped`, or, at its next heartbeat, + `job ... vanished: lease expired while running`; +* the client of the lost job retries with the same key, `dedupe.py` still maps the key to the reused id and + swallows the resubmission (`dedupe hit ... not enqueued`), so the job never completes. + +## Evidence (logs/service.log) + +* lines 927-928: `accepted job=j-fff` is followed by `accepted job=j-000`, the id sequence wrapped. +* lines 123, 357, 553, 769: heartbeats `lease renewed job=j-014 worker=w4`; the export j-014 is running and leased. +* line 986: `accepted job=j-014 kind=thumbnail` - the same id is issued again while the export still holds it. +* line 1000: `ack job=j-014 worker=w4 attempts=0` (the export acks, but the record it deletes is the new job's, attempts=0). +* line 1009: `claim of unknown job j-014 by w1, dropped`; line 1496: `dedupe hit key=k-d3f091db job=j-014, not enqueued` + (the client retry of the lost thumbnail job is swallowed). +* line 1456: `accepted job=j-0a3` while the export on w5 is leased; line 1655: `job j-0a3 vanished: lease expired while running`. +* line 2870: `accepted job=j-280` while the export on w6 is leased; line 3055: `ack for unknown job j-280 worker=w2`. +* line 3991: `accepted job=j-3c7` reuses the id of the export on w4; line 4058: `job j-3c7 vanished`. + +Unrelated noise: the `queue_depth counter drifted` warnings, the transient `failed attempt` retries, the two `dead after 3 +attempts` errors and the lease expiry of j-194 (line 2857, a frozen worker) are different things. + +## Fix + +`IdGenerator.next_id()` no longer masks the sequence, so ids are never reused (they just grow to four hex digits and +more). `JobStore.put` now refuses to overwrite a record of a different job, so a future id collision fails loudly at +submit time instead of corrupting a running job. Regression tests: `tests/test_regression.py`. diff --git a/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/ids.py b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/ids.py new file mode 100644 index 00000000..24dc7237 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/ids.py @@ -0,0 +1,12 @@ +"""Job id generation.""" + + +class IdGenerator: + """Hands out ids like j-0a3, one per accepted job; an id is never handed out twice.""" + + def __init__(self, start=0): + self._seq = start + + def next_id(self): + self._seq += 1 + return "j-%03x" % self._seq diff --git a/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/store.py b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/store.py new file mode 100644 index 00000000..f6213566 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/sched/store.py @@ -0,0 +1,26 @@ +class JobStore: + """In-memory job records, keyed by job id.""" + + def __init__(self): + self._jobs = {} + + def put(self, job): + old = self._jobs.get(job.id) + if old is not None and old is not job: + raise KeyError("job id %s is already in use" % job.id) + self._jobs[job.id] = job + + def get(self, job_id): + return self._jobs.get(job_id) + + def delete(self, job_id): + return self._jobs.pop(job_id, None) + + def __contains__(self, job_id): + return job_id in self._jobs + + def __len__(self): + return len(self._jobs) + + def count(self, status): + return sum(1 for job in self._jobs.values() if job.status == status) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/tests/test_regression.py b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/tests/test_regression.py new file mode 100644 index 00000000..db809ddb --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/reference/overlay/tests/test_regression.py @@ -0,0 +1,31 @@ +import unittest + +from helpers import make_scheduler, submit +from sched.ids import IdGenerator + + +class IdReuseRegression(unittest.TestCase): + def test_ids_do_not_repeat_over_many_jobs(self): + gen = IdGenerator() + seen = set() + for _ in range(10000): + job_id = gen.next_id() + self.assertNotIn(job_id, seen) + seen.add(job_id) + + def test_running_job_survives_the_id_space_being_cycled(self): + s = make_scheduler(lease_ttl=10 ** 9) + slow = submit(s, 0, kind="export") + job = s.claim("w4", ("export",)) + self.assertEqual(job.id, slow) + for n in range(1, 5000): + job_id = submit(s, n) + self.assertNotEqual(job_id, slow, "job %d got the id of the running export" % n) + s.claim("w1", ("email",)) + s.ack(job_id, "w1") + self.assertTrue(s.heartbeat(slow, "w4")) + self.assertTrue(s.ack(slow, "w4")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/run_sim.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/run_sim.py new file mode 100644 index 00000000..bbe94099 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/run_sim.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Replay a synthetic workload through the scheduler on a virtual clock. + + python3 run_sim.py --jobs 50000 --seed 3 + python3 run_sim.py --jobs 2000 --log /tmp/sim.log + +Prints a one-line JSON summary; the exit status is 1 when jobs were lost or ran twice. +""" + +import argparse +import json +import sys + +from sched.sim import Sim, SimConfig + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("--jobs", type=int, default=30000, help="number of client requests (default 30000)") + ap.add_argument("--seed", type=int, default=1) + ap.add_argument("--workers", type=int, default=3) + ap.add_argument("--slow-workers", type=int, default=1, help="workers that only serve the export lane") + ap.add_argument("--rate", type=float, default=1.0, help="new jobs per second") + ap.add_argument("--export-prob", type=float, default=1 / 6000) + ap.add_argument("--log", metavar="FILE", help="also write the service log to FILE") + args = ap.parse_args(argv) + + cfg = SimConfig( + jobs=args.jobs, + seed=args.seed, + workers=args.workers, + slow_workers=args.slow_workers, + rate=args.rate, + export_prob=args.export_prob, + keep_log=bool(args.log), + ) + sim = Sim(cfg) + summary = sim.run() + if args.log: + with open(args.log, "w") as fh: + fh.write("\n".join(sim.log.lines) + "\n") + print(json.dumps(summary, sort_keys=True)) + return 1 if summary["lost"] or summary["duplicated"] else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/__init__.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/__init__.py new file mode 100644 index 00000000..48d5fe9b --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/__init__.py @@ -0,0 +1 @@ +"""A small lease-based job scheduler with a deterministic simulator.""" diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/clock.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/clock.py new file mode 100644 index 00000000..2707e65c --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/clock.py @@ -0,0 +1,24 @@ +from datetime import datetime, timedelta + +EPOCH = datetime(2024, 5, 14, 6, 0, 0) + + +class VirtualClock: + """Simulated time in seconds since EPOCH; only the simulator moves it.""" + + def __init__(self, start=0.0): + self._now = start + + def now(self): + return self._now + + def advance_to(self, t): + if t < self._now: + raise ValueError("clock cannot go backwards: %.3f < %.3f" % (t, self._now)) + self._now = t + + +def format_ts(t): + ms = int(round(t * 1000)) + stamp = EPOCH + timedelta(milliseconds=ms) + return stamp.strftime("%Y-%m-%d %H:%M:%S") + ".%03d" % (ms % 1000) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/dedupe.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/dedupe.py new file mode 100644 index 00000000..f8999b1d --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/dedupe.py @@ -0,0 +1,24 @@ +class Deduper: + """Remembers idempotency keys for a while so client retries do not create second jobs.""" + + def __init__(self, window): + self.window = window + self._seen = {} + + def lookup(self, key, now): + entry = self._seen.get(key) + if entry is not None and now - entry[1] <= self.window: + return entry[0] + return None + + def remember(self, key, job_id, now): + self._seen[key] = (job_id, now) + + def prune(self, now): + stale = [k for k, (_job, ts) in self._seen.items() if now - ts > self.window] + for key in stale: + del self._seen[key] + return len(stale) + + def __len__(self): + return len(self._seen) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/ids.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/ids.py new file mode 100644 index 00000000..4048a683 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/ids.py @@ -0,0 +1,15 @@ +"""Job id generation.""" + +ID_BITS = 12 # three hex digits keep ids short enough to read out on a support call +ID_MASK = (1 << ID_BITS) - 1 + + +class IdGenerator: + """Hands out ids like j-0a3, one per accepted job.""" + + def __init__(self, start=0): + self._seq = start & ID_MASK + + def next_id(self): + self._seq = (self._seq + 1) & ID_MASK + return "j-%03x" % self._seq diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/lease.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/lease.py new file mode 100644 index 00000000..70889d8b --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/lease.py @@ -0,0 +1,38 @@ +class Lease: + def __init__(self, job_id, worker, expires): + self.job_id = job_id + self.worker = worker + self.expires = expires + + +class LeaseTable: + """Who is working on which job, and until when.""" + + def __init__(self, ttl): + self.ttl = ttl + self._leases = {} + + def grant(self, job_id, worker, now): + lease = Lease(job_id, worker, now + self.ttl) + self._leases[job_id] = lease + return lease + + def renew(self, job_id, now): + lease = self._leases.get(job_id) + if lease is None: + return False + lease.expires = now + self.ttl + return True + + def release(self, job_id): + return self._leases.pop(job_id, None) + + def expired(self, now): + return [lease for lease in self._leases.values() if lease.expires <= now] + + def holder(self, job_id): + lease = self._leases.get(job_id) + return lease.worker if lease else None + + def __len__(self): + return len(self._leases) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/logs.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/logs.py new file mode 100644 index 00000000..407dc132 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/logs.py @@ -0,0 +1,24 @@ +from .clock import format_ts + + +class Log: + """Collects log lines stamped with the virtual clock.""" + + def __init__(self, clock, enabled=True): + self.clock = clock + self.enabled = enabled + self.lines = [] + + def _emit(self, level, comp, msg, args): + if self.enabled: + text = msg % args if args else msg + self.lines.append("%s %-5s %-8s %s" % (format_ts(self.clock.now()), level, comp, text)) + + def info(self, comp, msg, *args): + self._emit("INFO", comp, msg, args) + + def warn(self, comp, msg, *args): + self._emit("WARN", comp, msg, args) + + def error(self, comp, msg, *args): + self._emit("ERROR", comp, msg, args) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/metrics.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/metrics.py new file mode 100644 index 00000000..69e0c4fb --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/metrics.py @@ -0,0 +1,34 @@ +class Metrics: + """Counters plus a queue depth gauge that is kept by hand and reconciled on flush.""" + + def __init__(self, log): + self.log = log + self.counters = {} + self.depth = 0 + + def inc(self, name, n=1): + self.counters[name] = self.counters.get(name, 0) + n + + def get(self, name): + return self.counters.get(name, 0) + + def flush(self, actual_depth, leased): + if self.depth != actual_depth: + self.log.warn( + "metrics", + "queue_depth counter drifted (counter=%d actual=%d), reconciling", + self.depth, + actual_depth, + ) + self.depth = actual_depth + self.log.info( + "metrics", + "queue_depth=%d leased=%d submitted=%d done=%d dead=%d retries=%d dedupe_hits=%d", + actual_depth, + leased, + self.get("submitted"), + self.get("done"), + self.get("dead"), + self.get("retries"), + self.get("dedupe_hits"), + ) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/model.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/model.py new file mode 100644 index 00000000..c2296977 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/model.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass, field +from typing import Optional + +QUEUED = "queued" +LEASED = "leased" +RETRY_WAIT = "retry_wait" +DONE = "done" +DEAD = "dead" + + +@dataclass +class Job: + id: str + kind: str + payload: dict + key: str + client: str + created_at: float + status: str = QUEUED + attempts: int = 0 + worker: Optional[str] = None diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/queue.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/queue.py new file mode 100644 index 00000000..98ca43b9 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/queue.py @@ -0,0 +1,35 @@ +from collections import deque + + +class JobQueue: + """FIFO queue with one lane per job kind; workers pop from the lanes they serve.""" + + def __init__(self): + self._lanes = {} + self._seq = 0 + self._size = 0 + + def push(self, job_id, kind): + self._seq += 1 + self._lanes.setdefault(kind, deque()).append((self._seq, job_id)) + self._size += 1 + + def pop(self, kinds): + """Oldest queued job id among the given kinds, or None.""" + best = None + for kind in kinds: + lane = self._lanes.get(kind) + if lane and (best is None or lane[0][0] < self._lanes[best][0][0]): + best = kind + if best is None: + return None + self._size -= 1 + return self._lanes[best].popleft()[1] + + def depth(self, kind=None): + if kind is None: + return self._size + return len(self._lanes.get(kind, ())) + + def __len__(self): + return self._size diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/retry.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/retry.py new file mode 100644 index 00000000..01833668 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/retry.py @@ -0,0 +1,14 @@ +class RetryPolicy: + """Exponential backoff with a cap.""" + + def __init__(self, max_attempts=3, base=2.0, factor=2.0, cap=30.0): + self.max_attempts = max_attempts + self.base = base + self.factor = factor + self.cap = cap + + def delay(self, attempt): + return min(self.cap, self.base * self.factor ** (attempt - 1)) + + def exhausted(self, attempts): + return attempts >= self.max_attempts diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/service.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/service.py new file mode 100644 index 00000000..98edaa15 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/service.py @@ -0,0 +1,158 @@ +"""The scheduler service: submit, claim, heartbeat, ack/fail and the lease reaper.""" + +from .dedupe import Deduper +from .ids import IdGenerator +from .lease import LeaseTable +from .metrics import Metrics +from .model import DEAD, DONE, LEASED, QUEUED, RETRY_WAIT, Job +from .queue import JobQueue +from .retry import RetryPolicy +from .store import JobStore + + +class Scheduler: + def __init__( + self, + clock, + log, + lease_ttl=120.0, + dedupe_window=900.0, + policy=None, + call_later=None, + on_complete=None, + on_dead=None, + ): + self.clock = clock + self.log = log + self.ids = IdGenerator() + self.store = JobStore() + self.queue = JobQueue() + self.leases = LeaseTable(lease_ttl) + self.dedupe = Deduper(dedupe_window) + self.policy = policy or RetryPolicy() + self.metrics = Metrics(log) + self.call_later = call_later + self.on_complete = on_complete + self.on_dead = on_dead + + def submit(self, kind, payload, key, client): + """Accept a job; a repeated key returns the id of the earlier submission.""" + now = self.clock.now() + known = self.dedupe.lookup(key, now) + if known is not None: + self.metrics.inc("dedupe_hits") + self.log.info("service", "dedupe hit key=%s job=%s, not enqueued", key, known) + return known + job = Job(self.ids.next_id(), kind, payload, key, client, now) + self.store.put(job) + self.queue.push(job.id, kind) + self.dedupe.remember(key, job.id, now) + self.metrics.inc("submitted") + self.metrics.depth += 1 + self.log.info("service", "accepted job=%s kind=%s client=%s key=%s", job.id, kind, client, key) + return job.id + + def claim(self, worker, kinds): + """Hand the oldest matching job to a worker and lease it.""" + while True: + job_id = self.queue.pop(kinds) + if job_id is None: + return None + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "claim of unknown job %s by %s, dropped", job_id, worker) + continue + job.status = LEASED + job.worker = worker + job.attempts += 1 + self.leases.grant(job.id, worker, self.clock.now()) + self.metrics.depth -= 1 + self.log.info( + "lease", "lease granted job=%s worker=%s ttl=%ds attempt=%d", job.id, worker, self.leases.ttl, job.attempts + ) + return job + + def heartbeat(self, job_id, worker): + """Extend the lease of a running job; False means the job is gone.""" + if self.store.get(job_id) is None: + return False + if not self.leases.renew(job_id, self.clock.now()): + return False + self.log.info("lease", "lease renewed job=%s worker=%s ttl=%ds", job_id, worker, self.leases.ttl) + return True + + def ack(self, job_id, worker): + """A worker finished a job: drop the record and report the completion.""" + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "ack for unknown job %s worker=%s", job_id, worker) + return False + job.status = DONE + self.store.delete(job_id) + self.leases.release(job_id) + self.metrics.inc("done") + self.log.info("service", "ack job=%s worker=%s attempts=%d", job_id, worker, job.attempts) + if self.on_complete: + self.on_complete(job) + return True + + def fail(self, job_id, worker, error): + """A worker reports a failed attempt: retry with backoff or give up.""" + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "failure report for unknown job %s worker=%s", job_id, worker) + return False + self.leases.release(job_id) + if self.policy.exhausted(job.attempts): + job.status = DEAD + self.store.delete(job_id) + self.metrics.inc("dead") + self.log.error("service", "job %s dead after %d attempts: %s", job_id, job.attempts, error) + if self.on_dead: + self.on_dead(job) + return False + delay = self.policy.delay(job.attempts) + job.status = RETRY_WAIT + self.metrics.inc("retries") + self.log.warn( + "service", + "job %s failed attempt=%d/%d: %s; retry in %.1fs", + job_id, + job.attempts, + self.policy.max_attempts, + error, + delay, + ) + self.call_later(delay, lambda: self.requeue(job_id)) + return True + + def requeue(self, job_id): + job = self.store.get(job_id) + if job is None: + self.log.warn("service", "requeue of unknown job %s", job_id) + return + job.status = QUEUED + job.worker = None + self.queue.push(job.id, job.kind) + self.log.info("service", "requeued job=%s attempt=%d", job.id, job.attempts + 1) + + def reap(self): + """Take back the jobs of workers that stopped renewing their lease.""" + now = self.clock.now() + for lease in self.leases.expired(now): + self.leases.release(lease.job_id) + job = self.store.get(lease.job_id) + if job is None: + self.log.warn("lease", "expired lease for unknown job %s worker=%s", lease.job_id, lease.worker) + continue + self.metrics.inc("lease_expired") + self.log.warn( + "lease", "lease expired job=%s worker=%s, no heartbeat for %ds; requeued", job.id, lease.worker, self.leases.ttl + ) + job.status = QUEUED + job.worker = None + self.queue.push(job.id, job.kind) + self.dedupe.prune(now) + + def flush_metrics(self): + self.metrics.flush(len(self.queue), len(self.leases)) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/sim.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/sim.py new file mode 100644 index 00000000..8bb97f66 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/sim.py @@ -0,0 +1,270 @@ +"""Deterministic discrete-event simulation of the scheduler. + +A virtual clock drives clients that submit jobs, workers that run them and the housekeeping timers +of the service. Everything is seeded, so a configuration always produces the same run. +""" + +import heapq +import itertools +import random +from dataclasses import dataclass, field +from typing import Dict, Optional, Tuple + +from .clock import VirtualClock +from .logs import Log +from .service import Scheduler +from .worker import Worker + +FAST_KINDS = ("email", "thumbnail", "invoice") +SLOW_KINDS = ("export",) +ERRORS = { + "email": "TimeoutError: upstream mailer timed out after 5s", + "thumbnail": "OSError: image decoder failed", + "invoice": "ConnectionError: ledger api unavailable", + "export": "MemoryError: report too large", +} + + +@dataclass +class SimConfig: + jobs: int = 30000 + seed: int = 1 + workers: int = 3 # the last `slow_workers` of them serve only the export lane + slow_workers: int = 1 + rate: float = 1.0 # new jobs per second + export_prob: float = 1 / 6000 + export_min: float = 2400.0 + export_max: float = 6000.0 + fail_prob: float = 0.01 # first attempt fails, the retry succeeds + dead_prob: float = 0.0005 # every attempt fails + heavy_prob: float = 0.004 # fast jobs that take 10-40 s + dup_prob: float = 0.03 # client sends the same request twice + hb_interval: float = 40.0 + lease_ttl: float = 120.0 + planted: Dict[int, float] = field(default_factory=dict) # job number -> export duration + overrides: Dict[int, float] = field(default_factory=dict) # job number -> duration + stalls: Dict[int, Tuple[float, float]] = field(default_factory=dict) # job number -> (offset, length) + fail_plan: Dict[int, int] = field(default_factory=dict) # job number -> failing attempts + keep_log: bool = False + log_from: Optional[int] = None # keep log lines from the moment this job number is submitted + log_extra: float = 20.0 # seconds to keep going after the last submission when log_from is set + + +class Plan: + """What the client submits and how the job will behave when a worker runs it.""" + + __slots__ = ("n", "kind", "payload", "key", "client", "dup_delay") + + +class Run: + __slots__ = ("token", "job", "start", "end", "stall") + + def __init__(self, token, job, start, end, stall): + self.token = token + self.job = job + self.start = start + self.end = end + self.stall = stall + + +class Sim: + def __init__(self, cfg): + self.cfg = cfg + self.clock = VirtualClock() + self.log = Log(self.clock, enabled=cfg.keep_log and cfg.log_from is None) + self.rng_arrival = random.Random(cfg.seed) + self.rng_tie = random.Random(cfg.seed + 7919) + self._heap = [] + self._seq = itertools.count() + self._tokens = itertools.count(1) + self._foreground = 0 + self._arrived = 0 + self._stop_at = None + self.service = Scheduler( + self.clock, + self.log, + lease_ttl=cfg.lease_ttl, + call_later=self.call_later, + on_complete=self._completed, + on_dead=self._dead, + ) + fast = cfg.workers - cfg.slow_workers + self.workers = [Worker("w%d" % (i + 1), FAST_KINDS, self.service, self.log) for i in range(fast)] + self.workers += [Worker("w%d" % (fast + i + 1), SLOW_KINDS, self.service, self.log) for i in range(cfg.slow_workers)] + self.runs = {} + self.credits = {} + self.dead = {} + self.executed = {} + self.vanished = 0 + self.events = 0 + + # ------------------------------------------------------------------ event loop + + def at(self, t, fn, *args, background=False): + if not background: + self._foreground += 1 + heapq.heappush(self._heap, (t, self.rng_tie.random(), next(self._seq), background, fn, args)) + + def call_later(self, delay, fn): + self.at(self.clock.now() + delay, fn) + + def run(self): + self.at(0.0, self.arrive) + self.at(10.0, self.tick_reap, background=True) + self.at(30.0, self.tick_flush, background=True) + while self._heap: + t, _tie, _seq, background, fn, args = heapq.heappop(self._heap) + if not background: + self._foreground -= 1 + elif self._foreground == 0: + break # only housekeeping timers are left + if self._stop_at is not None and t > self._stop_at: + break + self.clock.advance_to(t) + self.events += 1 + fn(*args) + return self.summary() + + # ------------------------------------------------------------------ clients + + def plan(self, n): + cfg = self.cfg + r = random.Random(cfg.seed * 1000003 + n) + p = Plan() + p.n = n + if n in cfg.planted: + p.kind, dur = "export", cfg.planted[n] + elif r.random() < cfg.export_prob: + p.kind, dur = "export", r.uniform(cfg.export_min, cfg.export_max) + else: + pick = r.random() + p.kind = "email" if pick < 0.55 else ("thumbnail" if pick < 0.85 else "invoice") + dur = {"email": r.uniform(0.3, 1.6), "thumbnail": r.uniform(0.8, 3.0), "invoice": r.uniform(0.5, 2.0)}[p.kind] + if r.random() < cfg.heavy_prob: + dur = r.uniform(10.0, 40.0) + dur = cfg.overrides.get(n, dur) + roll = r.random() + fail = 1 if roll < cfg.fail_prob else (99 if roll > 1.0 - cfg.dead_prob else 0) + fail = cfg.fail_plan.get(n, fail) + p.payload = {"n": n, "dur": dur, "fail": fail} + p.key = "k-%08x" % ((n * 2654435761 + cfg.seed) & 0xFFFFFFFF) + p.client = "c%03d" % r.randrange(1, 400) + p.dup_delay = r.uniform(2.0, 40.0) if r.random() < cfg.dup_prob else None + return p + + def arrive(self): + cfg = self.cfg + n = self._arrived + 1 + self._arrived = n + if cfg.log_from is not None and n == cfg.log_from: + self.log.enabled = True + p = self.plan(n) + now = self.clock.now() + self.service.submit(p.kind, p.payload, p.key, p.client) + if p.dup_delay is not None: + self.at(now + p.dup_delay, self.resubmit, p) + if p.kind != "export": + self.at(now + 90.0, self.check_timeout, p) + if n < cfg.jobs: + self.at(now + self.rng_arrival.expovariate(cfg.rate), self.arrive) + elif cfg.log_from is not None: + self._stop_at = now + cfg.log_extra + self.dispatch() + + def resubmit(self, p): + self.service.submit(p.kind, p.payload, p.key, p.client) + self.dispatch() + + def check_timeout(self, p): + """Clients that have seen no result after 90 s send the request again.""" + if not self.executed.get(p.n) and not self.dead.get(p.n): + self.resubmit(p) + + # ------------------------------------------------------------------ workers + + def dispatch(self): + if not len(self.service.queue): + return + for w in self.workers: + if w.idle: + job = w.poll() + if job is not None: + self.start(w, job) + + def start(self, w, job): + cfg = self.cfg + now = self.clock.now() + stall = cfg.stalls.get(job.payload["n"]) + end = now + job.payload["dur"] + (stall[1] if stall else 0.0) + token = next(self._tokens) + self.runs[w.name] = Run(token, job, now, end, stall) + self.at(end, self.finish, w, token) + if end - now > cfg.hb_interval: + self.at(now + cfg.hb_interval, self.beat, w, token) + + def beat(self, w, token): + run = self.runs.get(w.name) + if run is None or run.token != token: + return + now = self.clock.now() + frozen = run.stall is not None and run.start + run.stall[0] <= now < run.start + run.stall[0] + run.stall[1] + if not frozen and not w.heartbeat(): + del self.runs[w.name] + self.vanished += 1 + self.dispatch() + return + if now + self.cfg.hb_interval < run.end: + self.at(now + self.cfg.hb_interval, self.beat, w, token) + + def finish(self, w, token): + run = self.runs.get(w.name) + if run is None or run.token != token: + return + del self.runs[w.name] + job = run.job + n = job.payload["n"] + if job.attempts <= job.payload["fail"]: + w.fail(ERRORS[job.kind]) + else: + self.executed[n] = self.executed.get(n, 0) + 1 + w.complete() + self.dispatch() + + def _completed(self, job): + n = job.payload["n"] + self.credits[n] = self.credits.get(n, 0) + 1 + + def _dead(self, job): + n = job.payload["n"] + self.dead[n] = self.dead.get(n, 0) + 1 + + # ------------------------------------------------------------------ housekeeping + + def tick_reap(self): + self.service.reap() + self.dispatch() + self.at(self.clock.now() + 10.0, self.tick_reap, background=True) + + def tick_flush(self): + self.service.flush_metrics() + self.at(self.clock.now() + 30.0, self.tick_flush, background=True) + + # ------------------------------------------------------------------ result + + def summary(self): + n = self._arrived + lost = [i for i in range(1, n + 1) if not self.credits.get(i) and not self.dead.get(i)] + dup = [i for i in range(1, n + 1) if self.credits.get(i, 0) > 1 or self.executed.get(i, 0) > 1] + return { + "submitted": n, + "completed": sum(1 for i in range(1, n + 1) if self.credits.get(i)), + "dead": len(self.dead), + "lost": len(lost), + "lost_sample": lost[:5], + "duplicated": len(dup), + "vanished": self.vanished, + "lease_expired": self.service.metrics.get("lease_expired"), + "dedupe_hits": self.service.metrics.get("dedupe_hits"), + "virtual_seconds": round(self.clock.now(), 1), + "events": self.events, + } diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/store.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/store.py new file mode 100644 index 00000000..177466eb --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/store.py @@ -0,0 +1,24 @@ +class JobStore: + """In-memory job records, keyed by job id.""" + + def __init__(self): + self._jobs = {} + + def put(self, job): + # upsert: the retry path saves updated records through here as well + self._jobs[job.id] = job + + def get(self, job_id): + return self._jobs.get(job_id) + + def delete(self, job_id): + return self._jobs.pop(job_id, None) + + def __contains__(self, job_id): + return job_id in self._jobs + + def __len__(self): + return len(self._jobs) + + def count(self, status): + return sum(1 for job in self._jobs.values() if job.status == status) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/worker.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/worker.py new file mode 100644 index 00000000..607f65ba --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/sched/worker.py @@ -0,0 +1,55 @@ +"""Worker side of the protocol: claim, heartbeat, then ack or fail.""" + +SLOW_SECONDS = 10.0 +SLOW_SECONDS_BY_KIND = {"export": 7200.0} + + +class Worker: + def __init__(self, name, kinds, service, log): + self.name = name + self.kinds = tuple(kinds) + self.service = service + self.log = log + self.current = None + self.started_at = 0.0 + + @property + def idle(self): + return self.current is None + + def poll(self): + """Ask the scheduler for work; returns the claimed job or None.""" + job = self.service.claim(self.name, self.kinds) + if job is not None: + self.current = job + self.started_at = self.service.clock.now() + return job + + def heartbeat(self): + """Renew the lease of the running job; abandon the job if the scheduler lost it.""" + job = self.current + if self.service.heartbeat(job.id, self.name): + return True + self.log.error( + "worker", + "job %s vanished: lease expired while running (worker=%s kind=%s attempt=%d)", + job.id, + self.name, + job.kind, + job.attempts, + ) + self.current = None + return False + + def complete(self): + job = self.current + self.current = None + took = self.service.clock.now() - self.started_at + if took > SLOW_SECONDS_BY_KIND.get(job.kind, SLOW_SECONDS): + self.log.warn("worker", "slow job %s worker=%s kind=%s took %.1fs", job.id, self.name, job.kind, took) + return self.service.ack(job.id, self.name) + + def fail(self, error): + job = self.current + self.current = None + return self.service.fail(job.id, self.name, error) diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/helpers.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/helpers.py new file mode 100644 index 00000000..c60a2369 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/helpers.py @@ -0,0 +1,16 @@ +from sched.clock import VirtualClock +from sched.logs import Log +from sched.service import Scheduler + + +def make_scheduler(**kwargs): + clock = VirtualClock() + log = Log(clock) + later = [] + sched = Scheduler(clock, log, call_later=lambda delay, fn: later.append((clock.now() + delay, fn)), **kwargs) + sched.pending = later + return sched + + +def submit(sched, n, kind="email"): + return sched.submit(kind, {"n": n}, "key-%d" % n, "c001") diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_ids.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_ids.py new file mode 100644 index 00000000..4dbe51f0 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_ids.py @@ -0,0 +1,27 @@ +import unittest + +from sched.ids import IdGenerator + + +class IdGeneratorTests(unittest.TestCase): + def test_first_ids(self): + gen = IdGenerator() + self.assertEqual([gen.next_id() for _ in range(3)], ["j-001", "j-002", "j-003"]) + + def test_ids_are_hex(self): + gen = IdGenerator(start=0x0A2) + self.assertEqual(gen.next_id(), "j-0a3") + + def test_ids_are_unique_for_a_while(self): + gen = IdGenerator() + ids = [gen.next_id() for _ in range(2000)] + self.assertEqual(len(set(ids)), 2000) + + def test_ids_sort_in_creation_order_within_a_page(self): + gen = IdGenerator() + ids = [gen.next_id() for _ in range(200)] + self.assertEqual(ids, sorted(ids)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_lease_dedupe.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_lease_dedupe.py new file mode 100644 index 00000000..a84d0a59 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_lease_dedupe.py @@ -0,0 +1,59 @@ +import unittest + +from sched.dedupe import Deduper +from sched.lease import LeaseTable +from sched.retry import RetryPolicy + + +class LeaseTests(unittest.TestCase): + def test_grant_and_expiry(self): + leases = LeaseTable(ttl=120) + leases.grant("j-001", "w1", now=10.0) + self.assertEqual(leases.holder("j-001"), "w1") + self.assertEqual(leases.expired(129.9), []) + self.assertEqual([l.job_id for l in leases.expired(130.0)], ["j-001"]) + + def test_renew_pushes_expiry(self): + leases = LeaseTable(ttl=120) + leases.grant("j-001", "w1", now=0.0) + self.assertTrue(leases.renew("j-001", now=100.0)) + self.assertEqual(leases.expired(200.0), []) + self.assertEqual(len(leases.expired(220.0)), 1) + + def test_renew_unknown_and_release(self): + leases = LeaseTable(ttl=60) + self.assertFalse(leases.renew("j-404", now=0.0)) + leases.grant("j-001", "w1", now=0.0) + self.assertIsNotNone(leases.release("j-001")) + self.assertEqual(len(leases), 0) + + +class DedupeTests(unittest.TestCase): + def test_hit_within_window(self): + d = Deduper(window=900) + d.remember("k1", "j-001", now=0.0) + self.assertEqual(d.lookup("k1", now=899.0), "j-001") + self.assertIsNone(d.lookup("k1", now=901.0)) + self.assertIsNone(d.lookup("k2", now=1.0)) + + def test_prune(self): + d = Deduper(window=100) + d.remember("k1", "j-001", now=0.0) + d.remember("k2", "j-002", now=90.0) + self.assertEqual(d.prune(now=150.0), 1) + self.assertEqual(len(d), 1) + + +class RetryTests(unittest.TestCase): + def test_backoff_is_capped(self): + p = RetryPolicy(max_attempts=5, base=2.0, factor=2.0, cap=10.0) + self.assertEqual([p.delay(a) for a in (1, 2, 3, 4)], [2.0, 4.0, 8.0, 10.0]) + + def test_exhausted(self): + p = RetryPolicy(max_attempts=3) + self.assertFalse(p.exhausted(2)) + self.assertTrue(p.exhausted(3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_service.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_service.py new file mode 100644 index 00000000..7e6d098c --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_service.py @@ -0,0 +1,97 @@ +import unittest + +from helpers import make_scheduler, submit +from sched.model import LEASED, RETRY_WAIT + + +class ServiceTests(unittest.TestCase): + def test_submit_claim_ack(self): + s = make_scheduler() + jid = submit(s, 1) + job = s.claim("w1", ("email",)) + self.assertEqual(job.id, jid) + self.assertEqual((job.status, job.worker, job.attempts), (LEASED, "w1", 1)) + self.assertTrue(s.ack(jid, "w1")) + self.assertNotIn(jid, s.store) + + def test_claim_respects_kinds(self): + s = make_scheduler() + submit(s, 1, kind="export") + self.assertIsNone(s.claim("w1", ("email", "thumbnail"))) + self.assertIsNotNone(s.claim("w3", ("export",))) + + def test_duplicate_key_is_not_enqueued_twice(self): + s = make_scheduler() + a = s.submit("email", {"n": 1}, "same-key", "c001") + b = s.submit("email", {"n": 1}, "same-key", "c001") + self.assertEqual(a, b) + self.assertEqual(len(s.queue), 1) + self.assertEqual(s.metrics.get("dedupe_hits"), 1) + + def test_ack_of_unknown_job_is_reported(self): + s = make_scheduler() + self.assertFalse(s.ack("j-404", "w1")) + self.assertTrue(any("ack for unknown job j-404" in line for line in s.log.lines)) + + def test_heartbeat_keeps_the_lease_alive(self): + s = make_scheduler(lease_ttl=100) + jid = submit(s, 1) + s.claim("w1", ("email",)) + s.clock.advance_to(80.0) + self.assertTrue(s.heartbeat(jid, "w1")) + s.clock.advance_to(150.0) + s.reap() + self.assertEqual(s.store.get(jid).status, LEASED) + + def test_expired_lease_requeues_the_job(self): + s = make_scheduler(lease_ttl=100) + jid = submit(s, 1) + s.claim("w1", ("email",)) + s.clock.advance_to(101.0) + s.reap() + again = s.claim("w2", ("email",)) + self.assertEqual((again.id, again.attempts), (jid, 2)) + + def test_failure_schedules_a_retry(self): + s = make_scheduler() + jid = submit(s, 1) + s.claim("w1", ("email",)) + self.assertTrue(s.fail(jid, "w1", "boom")) + self.assertEqual(s.store.get(jid).status, RETRY_WAIT) + self.assertEqual(len(s.pending), 1) + when, fn = s.pending[0] + self.assertEqual(when, 2.0) + fn() + self.assertEqual(s.claim("w1", ("email",)).attempts, 2) + + def test_job_dies_after_max_attempts(self): + s = make_scheduler() + jid = submit(s, 1) + for _ in range(3): + s.claim("w1", ("email",)) + s.fail(jid, "w1", "boom") + if s.pending: + s.pending.pop()[1]() + self.assertNotIn(jid, s.store) + self.assertEqual(s.metrics.get("dead"), 1) + self.assertTrue(any("dead after 3 attempts" in line for line in s.log.lines)) + + def test_completion_callback(self): + done = [] + s = make_scheduler(on_complete=done.append) + jid = submit(s, 7) + s.claim("w1", ("email",)) + s.ack(jid, "w1") + self.assertEqual([j.payload["n"] for j in done], [7]) + + def test_metrics_flush_reconciles_the_depth_gauge(self): + s = make_scheduler() + submit(s, 1) + submit(s, 2) + s.flush_metrics() + self.assertEqual(s.metrics.depth, 2) + self.assertTrue(s.log.lines[-1].endswith("dedupe_hits=0")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_sim.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_sim.py new file mode 100644 index 00000000..ac047cc9 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_sim.py @@ -0,0 +1,41 @@ +import unittest + +from sched.clock import VirtualClock, format_ts +from sched.sim import Sim, SimConfig + + +class ClockTests(unittest.TestCase): + def test_format(self): + self.assertEqual(format_ts(0.0), "2024-05-14 06:00:00.000") + self.assertEqual(format_ts(3661.2504), "2024-05-14 07:01:01.250") + + def test_time_does_not_run_backwards(self): + clock = VirtualClock() + clock.advance_to(5.0) + with self.assertRaises(ValueError): + clock.advance_to(4.0) + + +class SimTests(unittest.TestCase): + def test_small_run_completes_every_job(self): + summary = Sim(SimConfig(jobs=500, seed=3)).run() + self.assertEqual(summary["submitted"], 500) + self.assertEqual(summary["lost"], 0) + self.assertEqual(summary["duplicated"], 0) + self.assertEqual(summary["completed"] + summary["dead"], 500) + + def test_same_seed_same_result(self): + a = Sim(SimConfig(jobs=300, seed=5)).run() + b = Sim(SimConfig(jobs=300, seed=5)).run() + self.assertEqual(a, b) + + def test_log_lines_are_stamped_and_ordered(self): + sim = Sim(SimConfig(jobs=100, seed=2, keep_log=True)) + sim.run() + stamps = [line[:23] for line in sim.log.lines] + self.assertEqual(stamps, sorted(stamps)) + self.assertIn("accepted job=j-001 ", sim.log.lines[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_store_queue.py b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_store_queue.py new file mode 100644 index 00000000..46c94f6c --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/seed/tests/test_store_queue.py @@ -0,0 +1,59 @@ +import unittest + +from sched.model import DONE, LEASED, Job +from sched.queue import JobQueue +from sched.store import JobStore + + +def make_job(job_id, kind="email"): + return Job(job_id, kind, {}, "k-" + job_id, "c001", 0.0) + + +class StoreTests(unittest.TestCase): + def test_put_get_delete(self): + store = JobStore() + store.put(make_job("j-001")) + self.assertIn("j-001", store) + self.assertEqual(store.get("j-001").kind, "email") + self.assertEqual(len(store), 1) + self.assertIsNotNone(store.delete("j-001")) + self.assertIsNone(store.get("j-001")) + self.assertIsNone(store.delete("j-001")) + + def test_count_by_status(self): + store = JobStore() + a, b = make_job("j-001"), make_job("j-002") + b.status = LEASED + store.put(a) + store.put(b) + self.assertEqual(store.count(LEASED), 1) + self.assertEqual(store.count(DONE), 0) + + +class QueueTests(unittest.TestCase): + def test_fifo_within_a_kind(self): + q = JobQueue() + for i in range(3): + q.push("j-00%d" % i, "email") + self.assertEqual([q.pop(("email",)) for _ in range(3)], ["j-000", "j-001", "j-002"]) + self.assertIsNone(q.pop(("email",))) + + def test_oldest_across_served_kinds(self): + q = JobQueue() + q.push("j-001", "thumbnail") + q.push("j-002", "email") + q.push("j-003", "export") + self.assertEqual(q.pop(("email", "thumbnail")), "j-001") + self.assertEqual(q.pop(("email", "thumbnail")), "j-002") + self.assertIsNone(q.pop(("email", "thumbnail"))) + self.assertEqual(q.pop(("export",)), "j-003") + + def test_depth(self): + q = JobQueue() + q.push("j-001", "email") + q.push("j-002", "export") + self.assertEqual((len(q), q.depth("email"), q.depth("export"), q.depth("invoice")), (2, 1, 1, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/debuglog-sched/task.md b/scripts/e2e/codex/tasks/debuglog-sched/task.md new file mode 100644 index 00000000..07ae4643 --- /dev/null +++ b/scripts/e2e/codex/tasks/debuglog-sched/task.md @@ -0,0 +1,39 @@ +--- +id: debuglog-sched +title: Find why a job scheduler loses jobs from a production log, fix it and write it up +kind: debug +expected_rounds: 20-50 +--- +# debuglog-sched + +Notes for the orchestrator (not sent to Codex). + +* Seed: `sched/` (a lease-based job scheduler: queue, store, leases, dedupe, retry, metrics, a discrete-event simulator, about 780 lines with `run_sim.py`), + 31 visible unit tests (green on the seed) and `logs/service.log` (4730 lines, 417 KB, generated by `gen_log.py` from the seed code; `gen_log.py` is not part of the seed). + Reading the log with grep/sed in slices is the realistic way; `cat`-ing it whole would be about 150k tokens, so context growth towards 100k tokens depends on how much of the log the agent pages through. +* The defect: `sched/ids.py` masks the id sequence to 12 bits (`ID_MASK`), so ids repeat after 4096 jobs. A long-running export job that still holds its lease gets its id issued again to a new job; + `JobStore.put` overwrites the record, so the first ack / heartbeat / claim after that finds nothing (`ack for unknown job`, `claim of unknown job ... dropped`, `job ... vanished: lease expired while running`), + and the client's retry is swallowed by `dedupe.py` (`dedupe hit ... not enqueued`). The log shows the sequence going `j-fff` -> `j-000` (line 927-928), heartbeats of the old job before the reuse, + and four incidents (lines 986/1009, 1456/1655, 2870/3055, 3991/4058). +* Red herrings in the log: transient `failed attempt` retries, `queue_depth counter drifted` warnings (a harmless hand-kept gauge), slow-job warnings, two `dead after 3 attempts` errors, + and one frozen worker whose lease expires (line 2857) which also yields an `ack for unknown job`-like pattern (`claim of unknown job j-194`), but with a `lease expired` line before it and no id reuse. +* Acceptance (`accept.py`): (1) the pristine visible tests (`hidden/tests`, copied over `tests/`) pass on the agent's code; (2) `tests/test_regression.py` exists and passes; (3) the same file FAILS against the original + `sched/` (`hidden/orig/sched`), so a test that cannot detect the bug is rejected; (4) two hidden stress simulations (140,000 jobs / 3 workers, 100,000 jobs / 5 workers, different seeds and traffic) run with the pristine + `sim.py` on top of the agent's service code and must lose and duplicate nothing (about 5 s each); (5) `FINDINGS.md` names `ids.py` and `next_id`/`IdGenerator`, talks about wrap/reuse/collision, and cites a number within 2 of an + evidence line (`hidden/evidence.json`, written by `gen_log.py`). Any fix that stops ids from colliding passes (removing the mask, skipping ids in use, a wider counter, uuid-like ids that keep the pristine tests green). + Because the pristine `sim.py` is used, a fix must keep the `Scheduler` constructor and method signatures. +* The original code loses 18 jobs in stress a and 27 in stress b; the reference fix (`reference/overlay`) loses none. Deterministic: seeded virtual-clock simulation, no wall clock, no network; Python 3.9 .. 3.14. +* To regenerate the log (not needed): `python3 gen_log.py` writes `seed/logs/service.log` and `hidden/evidence.json`; the output is byte-identical on Python 3.9 and 3.12. + +## Prompt + +Production lost some jobs. Customers are complaining that some of their jobs never completed, and on-call saw `ack for unknown job` warnings and `vanished` errors in the scheduler log. The log of the incident is `logs/service.log` (about 4,700 lines, so use grep and sed to look at slices of it rather than printing the whole file). The scheduler code is in `sched/`; `run_sim.py` replays a synthetic workload through the same code on a virtual clock (`python3 run_sim.py --help`), and the unit tests run with `python3 -m unittest discover -s tests`. + +Please: +1. Find the root cause of the lost jobs. The log has enough information to localise it. +2. Fix it in the code. Keep the existing tests green. +3. Add a regression test in `tests/test_regression.py` that fails on the old code and passes with your fix. +4. Write `FINDINGS.md` in the repository root with the root cause (file and function), the evidence (line numbers in `logs/service.log`) and the fix you made. + +There is no network here and only the Python 3 standard library is available (no pytest). When you are done, reply with a short summary of the root cause and the fix. + diff --git a/scripts/e2e/codex/tasks/feature-query/accept.py b/scripts/e2e/codex/tasks/feature-query/accept.py new file mode 100644 index 00000000..f3b94289 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/accept.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Acceptance check for task feature-query. + +Usage: python3 accept.py WORKSPACE +Exit 0 when the task is done; any other exit code means not done. The workspace is never modified: everything runs in a temporary copy. +""" + +import ast +import hashlib +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PRISTINE = HERE / "hidden" / "pristine_tests" +HIDDEN_TESTS = HERE / "hidden" / "test_hidden_spec.py" +SPEC_SHA256 = hashlib.sha256((HERE / "seed" / "SPEC.md").read_bytes()).hexdigest() +MIN_TEST_METHODS = 25 +IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".git") + +failed = [] + + +def check(name, ok, detail=""): + if ok: + print("PASS " + name) + else: + print("FAIL %s :: %s" % (name, detail.strip()[-1500:])) + failed.append(name) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def run_unittest(cwd, start_dir, pattern="test*.py", timeout=100): + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0") + try: + proc = subprocess.run( + [sys.executable, "-m", "unittest", "discover", "-s", start_dir, "-p", pattern], + cwd=str(cwd), env=env, capture_output=True, text=True, timeout=timeout, + ) + except subprocess.TimeoutExpired: + return False, "timeout", 0 + output = proc.stdout + proc.stderr + match = re.search(r"^Ran (\d+) tests? in", output, re.M) + return proc.returncode == 0, output, int(match.group(1)) if match else 0 + + +def count_assertive_tests(path): + """Number of test methods (in classes) that contain at least one assertion call.""" + tree = ast.parse(Path(path).read_text(encoding="utf-8")) + total = 0 + for node in ast.walk(tree): + if not isinstance(node, ast.ClassDef): + continue + for item in node.body: + if isinstance(item, ast.FunctionDef) and item.name.startswith("test"): + asserts = [ + n for n in ast.walk(item) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) + and (n.func.attr.startswith("assert") or n.func.attr in ("fail", "subTest")) + ] + if asserts: + total += 1 + return total + + +def main(): + if len(sys.argv) != 2: + print("usage: accept.py WORKSPACE") + return 2 + workspace = Path(sys.argv[1]).resolve() + if not workspace.is_dir(): + print("FAIL workspace :: not a directory") + return 2 + + # 1. pristine tests and the specification are untouched + for src in sorted(PRISTINE.rglob("*")): + if not src.is_file() or "__pycache__" in src.parts: + continue + rel = src.relative_to(PRISTINE) + target = workspace / "tests" / rel + check("tests-untouched:" + rel.as_posix(), target.is_file() and digest(target) == digest(src), + "tests/%s is missing or was modified" % rel.as_posix()) + spec = workspace / "SPEC.md" + check("spec-untouched", spec.is_file() and digest(spec) == SPEC_SHA256, "SPEC.md is missing or was modified") + + with tempfile.TemporaryDirectory() as tmp: + # 2. the existing behaviour, tested with the pristine tests only + pristine_ws = Path(tmp) / "pristine" + shutil.copytree(workspace, pristine_ws, ignore=IGNORE) + shutil.rmtree(pristine_ws / "tests", ignore_errors=True) + shutil.copytree(PRISTINE, pristine_ws / "tests", ignore=IGNORE) + ok, out, ran = run_unittest(pristine_ws, "tests") + check("existing-tests", ok and ran > 0, out) + + # 3. spec conformance, tested with hidden cases + hidden_dir = pristine_ws / "_hidden" + hidden_dir.mkdir() + shutil.copy(HIDDEN_TESTS, hidden_dir / "test_hidden_spec.py") + ok, out, ran = run_unittest(pristine_ws, "_hidden") + check("spec-conformance", ok and ran > 0, out) + + # 4. the agent's own tests + own = workspace / "tests" / "test_query.py" + exists = own.is_file() + check("own-tests-exist", exists, "tests/test_query.py does not exist") + if exists: + try: + assertive = count_assertive_tests(own) + except SyntaxError as exc: + assertive = 0 + print("note: tests/test_query.py does not parse: %s" % exc) + check("own-tests-count", assertive >= MIN_TEST_METHODS, + "%d test methods with assertions, need at least %d" % (assertive, MIN_TEST_METHODS)) + text = own.read_text(encoding="utf-8") + check("own-tests-use-feature", "minidb" in text and "where" in text, + "tests/test_query.py does not exercise the where language") + own_ws = Path(tmp) / "own" + shutil.copytree(workspace, own_ws, ignore=IGNORE) + ok, out, ran = run_unittest(own_ws, "tests", pattern="test_query.py") + check("own-tests-pass", ok and ran >= MIN_TEST_METHODS, "ran %d tests; %s" % (ran, out)) + + # 5. documentation + readme = workspace / "README.md" + text = readme.read_text(encoding="utf-8") if readme.is_file() else "" + check("readme-mentions-where-option", "--where" in text, "README.md does not mention --where") + + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_csv_cli.py b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_csv_cli.py new file mode 100644 index 00000000..6dd597f7 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_csv_cli.py @@ -0,0 +1,133 @@ +import contextlib +import io +import os +import tempfile +import unittest + +from minidb import Column, Database +from minidb.cli import main, parse_assignments, parse_column_spec +from minidb.csvio import export_csv, import_csv, read_csv, write_csv +from minidb.errors import SchemaError + + +def people_table(): + db = Database() + people = db.create_table("people", [Column("name"), Column("age", "int"), Column("active", "bool")]) + people.insert_many([ + {"name": "Ann", "age": 31, "active": True}, + {"name": "Bob, Jr.", "age": None, "active": False}, + ]) + return people + + +class CsvTests(unittest.TestCase): + def test_write_csv_format(self): + people = people_table() + buffer = io.StringIO() + write_csv(people.select(), people.schema.names(), buffer) + self.assertEqual(buffer.getvalue(), 'id,name,age,active\n1,Ann,31,true\n2,"Bob, Jr.",,false\n') + + def test_round_trip_through_a_file(self): + people = people_table() + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "people.csv") + self.assertEqual(export_csv(people, path), 2) + other = Database().create_table("people", [Column("name"), Column("age", "int"), Column("active", "bool")]) + self.assertEqual(import_csv(other, path), 2) + self.assertEqual(other.select(), people.select()) + + def test_import_ignores_id_column_and_checks_header(self): + schema = people_table().schema + rows = read_csv(io.StringIO("id,name\n7,Zed\n"), schema) + self.assertEqual(rows, [{"name": "Zed"}]) + with self.assertRaises(SchemaError): + read_csv(io.StringIO("nombre\nZed\n"), schema) + + def test_export_with_callable_filter(self): + people = people_table() + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "out.csv") + written = export_csv(people, path, where=lambda row: row["active"], columns=["name"]) + with open(path, encoding="utf-8") as handle: + self.assertEqual(handle.read(), "name\nAnn\n") + self.assertEqual(written, 1) + + +class ParsingTests(unittest.TestCase): + def test_column_specs(self): + self.assertEqual(parse_column_spec("age:int"), Column("age", "int")) + self.assertEqual(parse_column_spec("name:str:required"), Column("name", "str", nullable=False)) + with self.assertRaises(SchemaError): + parse_column_spec("age") + with self.assertRaises(SchemaError): + parse_column_spec("age:int:maybe") + + def test_assignments(self): + schema = people_table().schema + self.assertEqual(parse_assignments(schema, ["name=Ann", "age=", "active=true"]), + {"name": "Ann", "age": None, "active": True}) + with self.assertRaises(SchemaError): + parse_assignments(schema, ["age"]) + + +class CliTests(unittest.TestCase): + def setUp(self): + self._folder = tempfile.TemporaryDirectory() + self.addCleanup(self._folder.cleanup) + self.db = os.path.join(self._folder.name, "test.json") + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(err): + code = main(["--db", self.db, *args], out=out) + return code, out.getvalue(), err.getvalue() + + def setup_table(self): + self.assertEqual(self.run_cli("create", "people", "name:str:required", "age:int", "city:str")[0], 0) + for assignments in (["name=Ann", "age=31", "city=Berlin"], ["name=Bob", "age=25"], ["name=Cid", "city=Rome"]): + self.assertEqual(self.run_cli("insert", "people", *assignments)[0], 0) + + def test_insert_prints_ids_and_select_prints_csv(self): + self.setup_table() + code, out, _ = self.run_cli("select", "people") + self.assertEqual(code, 0) + self.assertEqual(out, "id,name,age,city\n1,Ann,31,Berlin\n2,Bob,25,\n3,Cid,,Rome\n") + + def test_select_options(self): + self.setup_table() + _, out, _ = self.run_cli("select", "people", "--columns", "name,age", "--order-by", "age", "--desc", "--limit", "2") + self.assertEqual(out, "name,age\nAnn,31\nBob,25\n") + + def test_update_and_delete_by_id(self): + self.setup_table() + self.assertEqual(self.run_cli("update", "people", "--id", "2", "city=Paris", "age=")[1], "updated 1\n") + self.assertEqual(self.run_cli("delete", "people", "--id", "1")[1], "deleted 1\n") + self.assertEqual(self.run_cli("delete", "people", "--id", "77")[1], "deleted 0\n") + _, out, _ = self.run_cli("select", "people") + self.assertEqual(out, "id,name,age,city\n2,Bob,,Paris\n3,Cid,,Rome\n") + + def test_data_persists_between_runs(self): + self.setup_table() + self.assertTrue(os.path.exists(self.db)) + _, out, _ = self.run_cli("select", "people", "--columns", "id") + self.assertEqual(out.splitlines(), ["id", "1", "2", "3"]) + + def test_errors_exit_with_status_two(self): + self.setup_table() + for args in (["select", "nobody"], ["insert", "people", "age=3"], ["insert", "people", "name=X", "age=old"], + ["select", "people", "--order-by", "height"]): + code, out, err = self.run_cli(*args) + self.assertEqual((code, out), (2, ""), args) + self.assertTrue(err.startswith("error: "), args) + + def test_import_and_export(self): + self.setup_table() + path = os.path.join(self._folder.name, "people.csv") + self.assertEqual(self.run_cli("export-csv", "people", path), (0, "exported 3\n", "")) + self.assertEqual(self.run_cli("import-csv", "people", path), (0, "imported 3\n", "")) + _, out, _ = self.run_cli("select", "people", "--columns", "name") + self.assertEqual(out.splitlines(), ["name", "Ann", "Bob", "Cid", "Ann", "Bob", "Cid"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_index_storage.py b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_index_storage.py new file mode 100644 index 00000000..45543eb2 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_index_storage.py @@ -0,0 +1,72 @@ +import json +import os +import tempfile +import unittest + +from minidb.errors import MiniDBError +from minidb.index import HashIndex +from minidb.storage import JsonFileStorage, MemoryStorage + + +class HashIndexTests(unittest.TestCase): + def test_add_lookup_remove(self): + index = HashIndex("city") + index.add({"id": 2, "city": "Rome"}) + index.add({"id": 1, "city": "Rome"}) + index.add({"id": 3, "city": "Paris"}) + self.assertEqual(index.lookup("Rome"), [1, 2]) + index.remove({"id": 1, "city": "Rome"}) + self.assertEqual(index.lookup("Rome"), [2]) + self.assertEqual(index.lookup("Oslo"), []) + self.assertEqual(len(index), 2) + + def test_nulls_are_not_indexed(self): + index = HashIndex("city") + index.add({"id": 1, "city": None}) + self.assertEqual(index.lookup(None), []) + self.assertEqual(len(index), 0) + + def test_rebuild(self): + index = HashIndex("n") + index.add({"id": 9, "n": 1}) + index.rebuild([{"id": 1, "n": 5}, {"id": 2, "n": 5}]) + self.assertEqual(index.lookup(1), []) + self.assertEqual(index.lookup(5), [1, 2]) + + +class StorageTests(unittest.TestCase): + def test_memory_storage_keeps_copies(self): + storage = MemoryStorage() + self.assertIsNone(storage.load()) + data = {"tables": {"t": {"rows": [1]}}} + storage.save(data) + data["tables"]["t"]["rows"].append(2) + self.assertEqual(storage.load(), {"tables": {"t": {"rows": [1]}}}) + + def test_json_file_round_trip(self): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "db.json") + storage = JsonFileStorage(path) + self.assertIsNone(storage.load()) + storage.save({"tables": {}, "version": 1}) + self.assertEqual(storage.load(), {"tables": {}, "version": 1}) + self.assertFalse(os.path.exists(path + ".tmp")) + + def test_corrupt_file_is_reported(self): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "db.json") + with open(path, "w", encoding="utf-8") as handle: + handle.write("{not json") + with self.assertRaises(MiniDBError): + JsonFileStorage(path).load() + + def test_file_is_plain_json(self): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "db.json") + JsonFileStorage(path).save({"a": [1, 2]}) + with open(path, encoding="utf-8") as handle: + self.assertEqual(json.load(handle), {"a": [1, 2]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_schema.py b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_schema.py new file mode 100644 index 00000000..68f69a27 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_schema.py @@ -0,0 +1,94 @@ +import unittest + +from minidb.errors import SchemaError +from minidb.schema import Column, Schema, coerce_value, parse_text + + +class ColumnTests(unittest.TestCase): + def test_rejects_bad_names(self): + for name in ("", "1abc", "a-b", "a b", "id!"): + with self.assertRaises(SchemaError, msg=name): + Column(name) + + def test_rejects_reserved_words_in_any_case(self): + for name in ("and", "Not", "NULL", "between", "true"): + with self.assertRaises(SchemaError, msg=name): + Column(name) + + def test_names_starting_with_a_keyword_are_fine(self): + for name in ("note", "android", "island", "origin", "nullable", "in_stock"): + self.assertEqual(Column(name).name, name) + + def test_unknown_type(self): + with self.assertRaises(SchemaError): + Column("x", "decimal") + + def test_default_is_checked(self): + with self.assertRaises(SchemaError): + Column("x", "int", default="seven") + self.assertEqual(Column("x", "float", default=2).default, 2.0) + + +class CoerceTests(unittest.TestCase): + def test_int_rejects_bool_and_float(self): + column = Column("n", "int") + self.assertEqual(coerce_value(column, 5), 5) + with self.assertRaises(SchemaError): + coerce_value(column, True) + with self.assertRaises(SchemaError): + coerce_value(column, 5.5) + + def test_float_accepts_int(self): + value = coerce_value(Column("f", "float"), 3) + self.assertEqual(value, 3.0) + self.assertIsInstance(value, float) + + def test_null_needs_nullable_column(self): + self.assertIsNone(coerce_value(Column("s"), None)) + with self.assertRaises(SchemaError): + coerce_value(Column("s", nullable=False), None) + + def test_parse_text(self): + self.assertEqual(parse_text(Column("n", "int"), "42"), 42) + self.assertEqual(parse_text(Column("f", "float"), "2.5"), 2.5) + self.assertIs(parse_text(Column("b", "bool"), "TRUE"), True) + self.assertEqual(parse_text(Column("s"), "hello world"), "hello world") + self.assertIsNone(parse_text(Column("n", "int"), "")) + with self.assertRaises(SchemaError): + parse_text(Column("n", "int"), "4x") + with self.assertRaises(SchemaError): + parse_text(Column("b", "bool"), "yes") + + +class SchemaTests(unittest.TestCase): + def test_id_column_comes_first(self): + schema = Schema([Column("name"), Column("age", "int")]) + self.assertEqual(schema.names(), ["id", "name", "age"]) + self.assertTrue(schema.has("age")) + self.assertFalse(schema.has("height")) + + def test_duplicate_and_id_columns_are_rejected(self): + with self.assertRaises(SchemaError): + Schema([Column("a"), Column("a")]) + with self.assertRaises(SchemaError): + Schema([Column("id", "int")]) + + def test_build_row_applies_defaults(self): + schema = Schema([Column("name", nullable=False, default="n/a"), Column("age", "int")]) + self.assertEqual(schema.build_row({"age": 4}, 7), {"id": 7, "name": "n/a", "age": 4}) + + def test_build_row_rejects_unknown_columns_and_id(self): + schema = Schema([Column("name")]) + with self.assertRaises(SchemaError): + schema.build_row({"nam": "x"}, 1) + with self.assertRaises(SchemaError): + schema.build_row({"id": 5}, 1) + + def test_round_trip(self): + schema = Schema([Column("name", nullable=False), Column("score", "float", default=1.5)]) + again = Schema.from_dict(schema.to_dict()) + self.assertEqual(again.columns, schema.columns) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_table.py b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_table.py new file mode 100644 index 00000000..499db8c4 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/hidden/pristine_tests/test_table.py @@ -0,0 +1,175 @@ +import unittest + +from minidb import Column, Database, JsonFileStorage, MemoryStorage +from minidb.errors import RowNotFound, SchemaError, TableError + + +def make_people(): + db = Database() + people = db.create_table("people", [ + Column("name", "str", nullable=False), + Column("age", "int"), + Column("city", "str"), + ]) + people.insert_many([ + {"name": "Ann", "age": 31, "city": "Berlin"}, + {"name": "Bob", "age": 25, "city": "Paris"}, + {"name": "Cid", "age": None, "city": "Berlin"}, + {"name": "Dee", "age": 40, "city": None}, + ]) + return people + + +class InsertTests(unittest.TestCase): + def test_ids_are_sequential_and_never_reused(self): + people = make_people() + self.assertEqual(people.insert(name="Eve"), 5) + people.delete(where=lambda row: row["id"] == 5) + self.assertEqual(people.insert(name="Fay"), 6) + + def test_missing_values_become_null(self): + people = make_people() + row = people.get(people.insert(name="Eve")) + self.assertEqual(row, {"id": 5, "name": "Eve", "age": None, "city": None}) + + def test_invalid_rows_are_rejected(self): + people = make_people() + with self.assertRaises(SchemaError): + people.insert(age=3) + with self.assertRaises(SchemaError): + people.insert(name="X", age="old") + self.assertEqual(len(people), 4) + + +class SelectTests(unittest.TestCase): + def setUp(self): + self.people = make_people() + + def names(self, rows): + return [row["name"] for row in rows] + + def test_select_all(self): + self.assertEqual(self.names(self.people.select()), ["Ann", "Bob", "Cid", "Dee"]) + + def test_select_with_callable(self): + rows = self.people.select(where=lambda row: row["city"] == "Berlin") + self.assertEqual(self.names(rows), ["Ann", "Cid"]) + + def test_returned_rows_are_copies(self): + row = self.people.select()[0] + row["name"] = "changed" + self.assertEqual(self.people.get(1)["name"], "Ann") + + def test_order_by_puts_nulls_last_in_both_directions(self): + self.assertEqual(self.names(self.people.select(order_by="age")), ["Bob", "Ann", "Dee", "Cid"]) + self.assertEqual(self.names(self.people.select(order_by="age", descending=True)), ["Dee", "Ann", "Bob", "Cid"]) + + def test_limit_and_columns(self): + rows = self.people.select(columns=["name", "id"], order_by="name", descending=True, limit=2) + self.assertEqual(rows, [{"name": "Dee", "id": 4}, {"name": "Cid", "id": 3}]) + + def test_unknown_columns_are_rejected(self): + with self.assertRaises(SchemaError): + self.people.select(order_by="height") + with self.assertRaises(SchemaError): + self.people.select(columns=["height"]) + + def test_where_must_be_callable_or_none(self): + with self.assertRaises(TypeError): + self.people.select(where=42) + + def test_count(self): + self.assertEqual(self.people.count(), 4) + self.assertEqual(self.people.count(where=lambda row: row["age"] is None), 1) + + def test_get_unknown_id(self): + with self.assertRaises(RowNotFound): + self.people.get(99) + + +class UpdateDeleteTests(unittest.TestCase): + def setUp(self): + self.people = make_people() + + def test_update_matching_rows(self): + changed = self.people.update({"city": "Rome"}, where=lambda row: row["city"] == "Berlin") + self.assertEqual(changed, 2) + self.assertEqual([r["city"] for r in self.people.select()], ["Rome", "Paris", "Rome", None]) + + def test_update_without_where_changes_everything(self): + self.assertEqual(self.people.update({"age": 1}), 4) + + def test_update_validates_before_changing(self): + with self.assertRaises(SchemaError): + self.people.update({"age": "x"}) + with self.assertRaises(SchemaError): + self.people.update({"id": 9}) + self.assertEqual(self.people.get(1)["age"], 31) + + def test_failed_predicate_changes_nothing(self): + def boom(row): + if row["id"] == 3: + raise ValueError("boom") + return True + + with self.assertRaises(ValueError): + self.people.update({"age": 0}, where=boom) + self.assertEqual(self.people.get(1)["age"], 31) + + def test_delete(self): + removed = self.people.delete(where=lambda row: row["age"] is None) + self.assertEqual(removed, 1) + self.assertEqual(len(self.people), 3) + self.assertEqual(self.people.delete(), 3) + + +class IndexTests(unittest.TestCase): + def test_index_follows_writes(self): + people = make_people() + people.create_index("city") + self.assertEqual([r["name"] for r in people.find("city", "Berlin")], ["Ann", "Cid"]) + people.update({"city": "Berlin"}, where=lambda row: row["name"] == "Bob") + people.insert(name="Eve", city="Berlin") + people.delete(where=lambda row: row["name"] == "Ann") + self.assertEqual([r["name"] for r in people.find("city", "Berlin")], ["Bob", "Cid", "Eve"]) + self.assertEqual(people.find("city", None), []) + + def test_find_without_index_matches_indexed_find(self): + plain, indexed = make_people(), make_people() + indexed.create_index("age") + self.assertEqual(plain.find("age", 25), indexed.find("age", 25)) + + def test_duplicate_index(self): + people = make_people() + people.create_index("city") + with self.assertRaises(TableError): + people.create_index("city") + + +class DatabaseTests(unittest.TestCase): + def test_tables(self): + db = Database() + db.create_table("a", [Column("x")]) + with self.assertRaises(TableError): + db.create_table("a", [Column("x")]) + with self.assertRaises(TableError): + db.table("b") + db.drop_table("a") + self.assertEqual(db.table_names(), []) + + def test_save_and_reload_keeps_rows_ids_and_indexes(self): + storage = MemoryStorage() + db = Database(storage) + people = db.create_table("people", [Column("name"), Column("age", "int")]) + people.insert_many([{"name": "Ann", "age": 3}, {"name": "Bob", "age": 4}]) + people.delete(where=lambda row: row["id"] == 2) + people.create_index("name") + db.save() + again = Database(storage).table("people") + self.assertEqual(again.select(), [{"id": 1, "name": "Ann", "age": 3}]) + self.assertEqual(again.indexed_columns(), ["name"]) + self.assertEqual(again.insert(name="Cy"), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/hidden/test_hidden_spec.py b/scripts/e2e/codex/tasks/feature-query/hidden/test_hidden_spec.py new file mode 100644 index 00000000..6b29eda9 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/hidden/test_hidden_spec.py @@ -0,0 +1,555 @@ +"""Spec conformance cases for the where language (all determined by SPEC.md alone).""" + +import contextlib +import io +import os +import tempfile +import unittest + +from minidb import Column, Database, JsonFileStorage +from minidb.cli import main +from minidb.errors import MiniDBError +from minidb.query import QueryError, QueryNameError, QuerySyntaxError, QueryTypeError, compile_where + +COLUMNS = ["id", "name", "age", "score", "active", "city", "note"] + +# name, age, score, active, city, note (ids 1..12 in this order) +PEOPLE = [ + ("Alice", 30, 88.5, True, "Berlin", "likes tea"), + ("Bob", 25, 72.0, False, "Paris", None), + ("Carol", None, 91.25, True, "Berlin", "50% done"), + ("Dave", 41, None, None, "London", "a_b"), + ("Eve", 35, 65.5, True, None, ""), + ("Frank", 19, 55.0, False, "Paris", "O'Brien"), + ("Grace", 30, 70.0, True, "Rome", "x"), + ("heidi", 52, 99.9, False, "Berlin", "Tea time"), + ("Ivan", 25, 72.0, None, "Rome", None), + ("Judy", 60, 40.0, True, "London", "100%"), + (None, 22, 50.0, False, "Paris", "anon"), + ("Mallory", 0, 0.0, True, "", "zero"), +] +ALL = list(range(1, 13)) + + +def make_people(): + table = Database().create_table("people", [ + Column("name"), Column("age", "int"), Column("score", "float"), + Column("active", "bool"), Column("city"), Column("note"), + ]) + for name, age, score, active, city, note in PEOPLE: + table.insert(name=name, age=age, score=score, active=active, city=city, note=note) + return table + + +SELECT_CASES = [ + # comparisons + ("age = 30", [1, 7]), + ("age != 30", [2, 4, 5, 6, 8, 9, 10, 11, 12]), + ("age <> 25", [1, 4, 5, 6, 7, 8, 10, 11, 12]), + ("age < 25", [6, 11, 12]), + ("age <= 25", [2, 6, 9, 11, 12]), + ("age > 40", [4, 8, 10]), + ("age >= 52", [8, 10]), + ("score > 70", [1, 2, 3, 8, 9]), + ("score >= 70", [1, 2, 3, 7, 8, 9]), + ("age = 30.0", [1, 7]), + ("score = 72", [2, 9]), + ("score = 88.50", [1]), + ("score = 0", [12]), + ("age = 0", [12]), + ("age = -0", [12]), + ("age = 007", []), + ("age = 99999999999999999999", []), + ("name = 'Alice'", [1]), + ("name = 'alice'", []), + ("name < 'C'", [1, 2]), + ("name >= 'h'", [8]), + ("note = 'O''Brien'", [6]), + ("note = ''", [5]), + ("city = ''", [12]), + ("'Paris' = city", [2, 6, 11]), + ("active = TRUE", [1, 3, 5, 7, 10, 12]), + ("active = FALSE", [2, 6, 8, 11]), + ("active", [1, 3, 5, 7, 10, 12]), + ("NOT active", [2, 6, 8, 11]), + ("active != TRUE", [2, 6, 8, 11]), + ("active > FALSE", [1, 3, 5, 7, 10, 12]), + # NULL handling + ("age = NULL", []), + ("age != NULL", []), + ("NOT (age = NULL)", []), + ("age IS NULL", [3]), + ("age IS NOT NULL", [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ("note IS NULL", [2, 9]), + ("city IS NULL", [5]), + ("active IS NULL", [4, 9]), + ("name IS NULL OR age IS NULL", [3, 11]), + ("score IS NULL AND active IS NULL", [4]), + ("NULL IS NULL", ALL), + ("5 IS NOT NULL", ALL), + ("NULL", []), + ("NOT NULL", []), + ("TRUE", ALL), + ("FALSE", []), + ("TRUE OR NULL", ALL), + ("FALSE OR NULL", []), + # logic and precedence + ("age > 30 OR active = TRUE", [1, 3, 4, 5, 7, 8, 10, 12]), + ("age > 30 AND active = TRUE", [5, 10]), + ("NOT (age > 30)", [1, 2, 6, 7, 9, 11, 12]), + ("NOT age > 30", [1, 2, 6, 7, 9, 11, 12]), + ("NOT age > 30 AND active", [1, 7, 12]), + ("age = 25 OR age = 30 AND active", [1, 2, 7, 9]), + ("(age = 25 OR age = 30) AND active", [1, 7]), + ("NOT (age = 25 OR age = 30)", [4, 5, 6, 8, 10, 11, 12]), + ("NOT NOT active", [1, 3, 5, 7, 10, 12]), + ("NOT active OR age > 50", [2, 6, 8, 10, 11]), + ("active AND NOT (age < 30)", [1, 5, 7, 10]), + ("NOT (age > 100 OR city = 'Paris')", [1, 4, 7, 8, 9, 10, 12]), + ("NOT (age > 0 AND city = 'Berlin')", [2, 4, 6, 7, 9, 10, 11, 12]), + ("city = 'Berlin' OR city = 'Rome' OR city = 'Paris'", [1, 2, 3, 6, 7, 8, 9, 11]), + ("age > 20 AND age < 40 AND active", [1, 5, 7]), + ("((((age = 30))))", [1, 7]), + ("(active) AND (city = 'Berlin')", [1, 3]), + # IN + ("age IN (25, 30)", [1, 2, 7, 9]), + ("age IN (25, 30, NULL)", [1, 2, 7, 9]), + ("age NOT IN (25, 30)", [4, 5, 6, 8, 10, 11, 12]), + ("age NOT IN (25, 30, NULL)", []), + ("city IN ('Rome', 'London')", [4, 7, 9, 10]), + ("city NOT IN ('Rome', 'London')", [1, 2, 3, 6, 8, 11, 12]), + ("score IN (72, 55.0)", [2, 6, 9]), + ("name IN ('Alice')", [1]), + ("active IN (TRUE)", [1, 3, 5, 7, 10, 12]), + ("age in (1, 2, 3, 30)", [1, 7]), + ("age IN (30, 30)", [1, 7]), + ("age IN(30,25)", [1, 2, 7, 9]), + ("NULL IN (1)", []), + ("NULL NOT IN (1)", []), + ("3 IN (1, 2, 3)", ALL), + ("id IN (2, 4, 6) AND NOT active", [2, 6]), + # BETWEEN + ("age BETWEEN 25 AND 35", [1, 2, 5, 7, 9]), + ("age NOT BETWEEN 25 AND 35", [4, 6, 8, 10, 11, 12]), + ("age BETWEEN 35 AND 25", []), + ("age BETWEEN 30 AND 30", [1, 7]), + ("age BETWEEN -5 AND 20", [6, 12]), + ("age BETWEEN 0 AND 100", [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ("score BETWEEN 50 AND 72", [2, 5, 6, 7, 9, 11]), + ("name BETWEEN 'B' AND 'D'", [2, 3]), + ("age BETWEEN 20 AND 40 AND active", [1, 5, 7]), + ("active AND age BETWEEN 20 AND 40", [1, 5, 7]), + ("age BETWEEN 25 AND 35 OR city = 'London'", [1, 2, 4, 5, 7, 9, 10]), + ("age BETWEEN NULL AND 30", []), + ("age BETWEEN 1 AND NULL", []), + ("age NOT BETWEEN 1 AND NULL", [12]), + # LIKE and ILIKE + ("name LIKE 'A%'", [1]), + ("name LIKE '%e'", [1, 4, 5, 7]), + ("name LIKE '_ob'", [2]), + ("name LIKE '____'", [4, 9, 10]), + ("name LIKE 'alice'", []), + ("name ILIKE 'alice'", [1]), + ("name ILIKE 'H%'", [8]), + ("name LIKE 'h%'", [8]), + ("name LIKE 'H%'", []), + ("name LIKE '%'", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]), + ("name LIKE '%a%'", [3, 4, 6, 7, 9, 12]), + ("name ILIKE '%A%'", [1, 3, 4, 6, 7, 9, 12]), + ("note LIKE '50%'", [3]), + ("note LIKE '%0%'", [3, 10]), + ("note LIKE 'a_b'", [4]), + ("note LIKE 'a__'", [4]), + ("note LIKE ''", [5]), + ("note LIKE '%'", [1, 3, 4, 5, 6, 7, 8, 10, 11, 12]), + ("note NOT LIKE '%tea%'", [3, 4, 5, 6, 7, 8, 10, 11, 12]), + ("note ILIKE '%tea%'", [1, 8]), + ("note NOT ILIKE '%tea%'", [3, 4, 5, 6, 7, 10, 11, 12]), + ("note LIKE '%''%'", [6]), + ("note LIKE note", [1, 3, 4, 5, 6, 7, 8, 10, 11, 12]), + ("name LIKE NULL", []), + ("name LIKE '.%'", []), + ("name LIKE '[A-C]%'", []), + ("name LIKE 'A.ice'", []), + ("note LIKE '%.%'", []), + # layout and tokens + (" age =\t30\n", [1, 7]), + ("age>=30", [1, 4, 5, 7, 8, 10]), + ("age<=-1", []), + ("age<>30", [2, 4, 5, 6, 8, 9, 10, 11, 12]), + ("(age=30)AND(active)", [1, 7]), + ("NOT(age=30)", [2, 4, 5, 6, 8, 9, 10, 11, 12]), + ("name='Alice'", [1]), + ("age Is Not NuLL", [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ("note IS NULL", [2, 9]), + # operands not reached are not type checked + ("id < 0 AND name = 5", []), + ("id > 0 OR name = 5", ALL), + ("FALSE AND name = 5", []), + ("TRUE OR age = 'x'", ALL), + ("note IS NULL AND note = 5", []), + ("age = NULL OR note = NULL", []), +] + +SYNTAX_ERROR_CASES = [ + ("", 0), + (" ", 3), + ("age >", 5), + ("age > 5 AND", 11), + ("age = 1 OR", 10), + ("(", 1), + ("()", 1), + ("NOT", 3), + ("(age = 1", 8), + ("age = = 1", 6), + ("age == 1", 5), + ("age = 1)", 7), + ("age = 1 name = 2", 8), + ("age = 1 2", 8), + ("age IN ()", 8), + ("age IN (1,)", 10), + ("age IN (1 2)", 10), + ("age IN (1, 'a', )", 16), + ("age IN (foo)", 8), + ("age IN 1", 7), + ("age BETWEEN 1 2", 14), + ("age BETWEEN 1", 13), + ("age BETWEEN AND 5", 12), + ("age NOT 5", 8), + ("age NOT NOT IN (1)", 8), + ("age NOT", 7), + ("age IS 5", 7), + ("age IS NOT 5", 11), + ("age IS NULL NULL", 12), + ("age LIKE", 8), + ("= 5", 0), + ("AND age = 1", 0), + ("age = 1 AND AND age = 2", 12), + ("age (= 1)", 4), + ("age < > 1", 6), + ("age =< 1", 5), + ("age = 5 -3", 8), + ("(age = 1) 5", 10), + ("(age) = 1", 6), + ("age = (1)", 6), + ("age\t=\n=", 6), + # lexical errors + ("age = 'abc", 6), + ("age = 'it''", 6), + ("age = 1 # comment", 8), + ("age ! 1", 4), + ("age = - 5", 6), + ("age = 5 - 3", 8), + ("age = 1.", 7), + ("age = .5", 6), + ("age = 1.5.2", 9), + ("\u00e9 = 1", 0), + ("name = 'caf\u00e9' $", 14), + ("age = = 1 'oops", 10), +] + +NAME_ERROR_CASES = [ + ("agee > 5", "agee", 0), + ("age > 5 AND foo = 1", "foo", 12), + ("Age = 1", "Age", 0), + ("age = 1 AND (bar IS NULL OR baz = 1)", "bar", 13), + ("5 = zzz", "zzz", 4), + ("NOT missing", "missing", 4), + ("name LIKE other", "other", 10), + ("age BETWEEN lo AND hi", "lo", 12), + ("age = 1 OR id = 2 OR nope IS NULL", "nope", 21), +] + +TYPE_ERROR_QUERIES = [ + "name = 5", "age = 'x'", "age = '30'", "active = 1", "age > TRUE", "score = 'x'", "NOT name = 5", + "age", "name", "5", "'abc'", "name LIKE 5", "age LIKE '3%'", "note ILIKE 3", + "age IN (1, 'a')", "active IN (1)", "age BETWEEN 'a' AND 5", "name BETWEEN 1 AND 2", + "age > 100 AND name = 5", "city = 5 AND FALSE", +] + + +class SelectSpec(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.people = make_people() + + def test_select_cases(self): + for text, expected in SELECT_CASES: + with self.subTest(query=text): + self.assertEqual([r["id"] for r in self.people.select(where=text)], expected) + + def test_compile_where_agrees_with_select(self): + rows = self.people.select() + for text, expected in SELECT_CASES[:60]: + with self.subTest(query=text): + predicate = compile_where(text, COLUMNS) + self.assertEqual([r["id"] for r in rows if predicate(r)], expected) + + def test_predicate_returns_real_booleans(self): + predicate = compile_where("age = NULL", COLUMNS) + self.assertIs(predicate({"age": 1}), False) + self.assertIs(predicate({"age": None}), False) + self.assertIs(compile_where("age > 0", COLUMNS)({"age": 1}), True) + + +class ErrorSpec(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.people = make_people() + + def test_syntax_error_positions(self): + for text, position in SYNTAX_ERROR_CASES: + with self.subTest(query=text): + with self.assertRaises(QuerySyntaxError) as caught: + compile_where(text, COLUMNS) + self.assertEqual(caught.exception.position, position) + self.assertTrue(str(caught.exception).endswith("at position %d" % position), str(caught.exception)) + + def test_syntax_errors_come_through_the_table(self): + for text, position in SYNTAX_ERROR_CASES[:12]: + with self.subTest(query=text): + with self.assertRaises(QuerySyntaxError) as caught: + self.people.select(where=text) + self.assertEqual(caught.exception.position, position) + + def test_name_errors(self): + for text, name, position in NAME_ERROR_CASES: + with self.subTest(query=text): + with self.assertRaises(QueryNameError) as caught: + compile_where(text, COLUMNS) + self.assertEqual((caught.exception.name, caught.exception.position), (name, position)) + + def test_name_error_does_not_need_rows(self): + empty = Database().create_table("t", [Column("age", "int")]) + with self.assertRaises(QueryNameError): + empty.select(where="height > 1") + with self.assertRaises(QueryNameError): + empty.count(where="height > 1") + + def test_syntax_error_beats_name_error(self): + for text, position in (("foo = ", 6), ("foo bar", 4), ("(foo = 1", 8), ("foo = 1 'x", 8)): + with self.subTest(query=text): + with self.assertRaises(QuerySyntaxError) as caught: + compile_where(text, COLUMNS) + self.assertEqual(caught.exception.position, position) + + def test_type_errors(self): + for text in TYPE_ERROR_QUERIES: + with self.subTest(query=text): + with self.assertRaises(QueryTypeError): + self.people.select(where=text) + + def test_type_errors_are_raised_when_evaluating_not_compiling(self): + for text in TYPE_ERROR_QUERIES: + with self.subTest(query=text): + predicate = compile_where(text, COLUMNS) + self.assertTrue(callable(predicate)) + + def test_type_error_needs_a_row_that_reaches_it(self): + predicate = compile_where("x = 5", ["x"]) + self.assertIs(predicate({"x": None}), False) + self.assertIs(predicate({"x": 5}), True) + with self.assertRaises(QueryTypeError): + predicate({"x": "a"}) + only_nulls = Database().create_table("t", [Column("age", "int")]) + only_nulls.insert_many([{"age": None}, {"age": None}]) + self.assertEqual(only_nulls.select(where="age = 'x'"), []) + empty = Database().create_table("t", [Column("age", "int")]) + self.assertEqual(empty.select(where="age = 'x'"), []) + + def test_short_circuit_in_in_and_between(self): + table = Database().create_table("t", [Column("age", "int")]) + table.insert(age=30) + self.assertEqual([r["id"] for r in table.select(where="age IN (30, 'a')")], [1]) + self.assertEqual([r["id"] for r in table.select(where="age IN (30, NULL, 'a')")], [1]) + self.assertEqual(table.select(where="age NOT IN (30, 'a')"), []) + self.assertEqual(table.select(where="age BETWEEN 40 AND 'z'"), []) + with self.assertRaises(QueryTypeError): + table.select(where="age IN (1, 'a')") + with self.assertRaises(QueryTypeError): + table.select(where="age BETWEEN 10 AND 'z'") + with self.assertRaises(QueryTypeError): + table.select(where="age BETWEEN 'a' AND 5") + + def test_unknown_does_not_short_circuit(self): + table = Database().create_table("t", [Column("age", "int"), Column("name")]) + table.insert(age=None, name="x") + with self.assertRaises(QueryTypeError): + table.select(where="age > 100 AND name = 5") + with self.assertRaises(QueryTypeError): + table.select(where="age > 100 OR name = 5") + + def test_class_hierarchy(self): + for cls in (QuerySyntaxError, QueryNameError, QueryTypeError): + self.assertTrue(issubclass(cls, QueryError)) + self.assertTrue(issubclass(QueryError, MiniDBError)) + + +class TableApiSpec(unittest.TestCase): + def setUp(self): + self.people = make_people() + + def ids(self, **kwargs): + return [r["id"] for r in self.people.select(**kwargs)] + + def test_callable_and_none_are_unchanged(self): + self.assertEqual(self.ids(), ALL) + self.assertEqual(self.ids(where=None), ALL) + self.assertEqual(self.ids(where=lambda row: row["age"] == 25), [2, 9]) + + def test_options_still_work_with_strings(self): + self.assertEqual(self.ids(where="age > 30", order_by="age", descending=True, limit=2), [10, 8]) + self.assertEqual(self.ids(where="age > 30", order_by="age"), [5, 4, 8, 10]) + rows = self.people.select(where="age > 30", columns=["name"], order_by="id") + self.assertEqual([r["name"] for r in rows], ["Dave", "Eve", "heidi", "Judy"]) + self.assertEqual(self.ids(where="city = 'Paris'", order_by="score"), [11, 6, 2]) + + def test_count(self): + self.assertEqual(self.people.count(where="active"), 6) + self.assertEqual(self.people.count(where="age > 30 AND active"), 2) + self.assertEqual(self.people.count(where="age = NULL"), 0) + self.assertEqual(self.people.count(), 12) + + def test_update(self): + self.assertEqual(self.people.update({"note": "seen"}, where="city = 'Paris'"), 3) + self.assertEqual(self.ids(where="note = 'seen'"), [2, 6, 11]) + self.assertEqual(self.people.update({"age": 99}, where="id <= 2"), 2) + self.assertEqual(self.ids(where="age = 99"), [1, 2]) + self.assertEqual(self.people.update({"age": 1}, where="FALSE"), 0) + + def test_delete(self): + self.assertEqual(self.people.delete(where="age IS NULL"), 1) + self.assertEqual(len(self.people), 11) + self.assertEqual(self.people.delete(where="active IS NULL OR age < 20"), 4) + self.assertEqual(self.ids(), [1, 2, 5, 7, 8, 10, 11]) + + def test_failed_queries_change_nothing(self): + before = self.people.select() + with self.assertRaises(QueryTypeError): + self.people.update({"age": 0}, where="age > 100 AND name = 5") + with self.assertRaises(QueryTypeError): + self.people.delete(where="name = 5") + with self.assertRaises(QuerySyntaxError): + self.people.update({"age": 0}, where="age >") + with self.assertRaises(QueryNameError): + self.people.delete(where="height > 1") + self.assertEqual(self.people.select(), before) + + def test_index_stays_consistent(self): + self.people.create_index("city") + self.assertEqual(self.people.update({"city": "Rome"}, where="city = 'Paris'"), 3) + self.assertEqual([r["id"] for r in self.people.find("city", "Rome")], [2, 6, 7, 9, 11]) + self.assertEqual(self.people.find("city", "Paris"), []) + self.people.delete(where="city = 'Rome' AND age > 20") + self.assertEqual([r["id"] for r in self.people.find("city", "Rome")], [6]) + + def test_blank_expression_is_a_syntax_error(self): + for call in ( + lambda: self.people.select(where=""), + lambda: self.people.count(where=" "), + lambda: self.people.update({"age": 1}, where=""), + lambda: self.people.delete(where="\n"), + ): + with self.assertRaises(QuerySyntaxError): + call() + + def test_other_types_still_raise_type_error(self): + for bad in (5, ["age > 1"], 1.5, {"age": 1}): + with self.assertRaises(TypeError): + self.people.select(where=bad) + with self.assertRaises(TypeError): + self.people.count(where=bad) + + +class CliSpec(unittest.TestCase): + def setUp(self): + self._folder = tempfile.TemporaryDirectory() + self.addCleanup(self._folder.cleanup) + self.path = os.path.join(self._folder.name, "people.json") + db = Database(JsonFileStorage(self.path)) + table = db.create_table("people", [ + Column("name"), Column("age", "int"), Column("score", "float"), + Column("active", "bool"), Column("city"), Column("note"), + ]) + for name, age, score, active, city, note in PEOPLE: + table.insert(name=name, age=age, score=score, active=active, city=city, note=note) + db.save() + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(err): + try: + code = main(["--db", self.path, *args], out=out) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, out.getvalue(), err.getvalue() + + def stored_ids(self): + table = Database(JsonFileStorage(self.path)).table("people") + return [r["id"] for r in table.select()] + + def test_select_where(self): + code, out, _ = self.run_cli("select", "people", "--where", "age > 40", "--columns", "id,name") + self.assertEqual((code, out), (0, "id,name\n4,Dave\n8,heidi\n10,Judy\n")) + + def test_select_where_with_order_and_limit(self): + code, out, _ = self.run_cli( + "select", "people", "--where", "city IN ('Paris', 'Rome') AND NOT active", + "--columns", "id", "--order-by", "score", "--desc", "--limit", "2", + ) + self.assertEqual((code, out), (0, "id\n2\n6\n")) + + def test_select_without_where_is_unchanged(self): + _, out, _ = self.run_cli("select", "people", "--columns", "id") + self.assertEqual(out.split(), ["id"] + [str(i) for i in ALL]) + + def test_update_where(self): + code, out, _ = self.run_cli("update", "people", "--where", "city = 'Paris'", "note=seen") + self.assertEqual((code, out), (0, "updated 3\n")) + table = Database(JsonFileStorage(self.path)).table("people") + self.assertEqual([r["id"] for r in table.select(where=lambda r: r["note"] == "seen")], [2, 6, 11]) + + def test_delete_where(self): + code, out, _ = self.run_cli("delete", "people", "--where", "active IS NULL") + self.assertEqual((code, out), (0, "deleted 2\n")) + self.assertEqual(self.stored_ids(), [1, 2, 3, 5, 6, 7, 8, 10, 11, 12]) + + def test_id_options_still_work(self): + self.assertEqual(self.run_cli("delete", "people", "--id", "12")[:2], (0, "deleted 1\n")) + self.assertEqual(self.run_cli("update", "people", "--id", "1", "age=31")[:2], (0, "updated 1\n")) + + def test_query_errors_exit_with_two(self): + cases = [ + ("age =", "position 5"), + ("", "position 0"), + ("height > 1", None), + ("name = 5", None), + ] + for text, fragment in cases: + with self.subTest(where=text): + code, out, err = self.run_cli("select", "people", "--where", text) + self.assertEqual((code, out), (2, "")) + self.assertTrue(err.startswith("error: "), err) + if fragment: + self.assertIn(fragment, err) + + def test_failed_update_and_delete_change_nothing(self): + self.assertEqual(self.run_cli("update", "people", "--where", "age >", "age=1")[0], 2) + self.assertEqual(self.run_cli("delete", "people", "--where", "name = 5")[0], 2) + self.assertEqual(self.stored_ids(), ALL) + + def test_id_and_where_are_mutually_exclusive_and_one_is_required(self): + for args in ( + ("delete", "people", "--id", "1", "--where", "age > 1"), + ("update", "people", "--id", "1", "--where", "age > 1", "age=2"), + ("delete", "people"), + ("update", "people", "age=2"), + ): + with self.subTest(args=args): + code, _, _ = self.run_cli(*args) + self.assertNotEqual(code, 0) + self.assertEqual(self.stored_ids(), ALL) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/reference/overlay/README.md b/scripts/e2e/codex/tasks/feature-query/reference/overlay/README.md new file mode 100644 index 00000000..3652bc8a --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/reference/overlay/README.md @@ -0,0 +1,78 @@ +# minidb + +A tiny in-process table store with JSON persistence. Pure Python 3, standard library only. + +## Library + +```python +from minidb import Column, Database, JsonFileStorage + +db = Database(JsonFileStorage("people.json")) # or Database() for an in-memory database +people = db.create_table("people", [ + Column("name", "str", nullable=False), + Column("age", "int"), + Column("city", "str"), +]) +person_id = people.insert(name="Ann", age=31, city="Berlin") +db.save() + +people.select(where=lambda row: row["age"] is not None and row["age"] > 30, order_by="name", limit=10) +people.update({"city": "Rome"}, where=lambda row: row["city"] == "Berlin") +people.delete(where=lambda row: row["age"] is None) +people.count() +``` + +* Column types are `int`, `float`, `str` and `bool`. Every table has an integer `id` column that is assigned automatically. +* `select(where=None, columns=None, order_by=None, descending=False, limit=None)` returns copies of the rows as dictionaries, in insertion order + unless `order_by` is given. Rows with NULL in the `order_by` column come last. +* `where` is a callable that receives the row dictionary; `None` means every row. +* `Table.create_index(column)` adds a hash index that speeds up `Table.find(column, value)`. +* Column names must be identifiers and must not be one of the reserved words `AND OR NOT IN BETWEEN LIKE ILIKE IS NULL TRUE FALSE`. + +## Command line + +```text +python3 -m minidb.cli --db people.json create people name:str:required age:int city:str +python3 -m minidb.cli --db people.json insert people name=Ann age=31 city=Berlin +python3 -m minidb.cli --db people.json select people --columns id,name --order-by age --desc --limit 5 +python3 -m minidb.cli --db people.json update people --id 1 city=Rome +python3 -m minidb.cli --db people.json delete people --id 1 +python3 -m minidb.cli --db people.json import-csv people people.csv +python3 -m minidb.cli --db people.json export-csv people out.csv +``` + +* `select` prints CSV (header line, then one line per row; NULL is an empty field, booleans are `true` / `false`). +* `column=` with nothing after the equals sign sets NULL. +* `update` and `delete` print `updated N` / `deleted N`. +* Errors print `error: ...` on standard error and the exit status is 2. + +## Tests + +```text +python3 -m unittest discover -s tests +``` + +## Query language + +`where` may also be a string in the query language specified in `SPEC.md`. It is available from `Table.select`, `Table.update`, +`Table.delete` and `Table.count`, from `minidb.query.compile_where`, and as `--where` on the command line. + +```python +people.select(where="age >= 18 AND city IN ('Berlin', 'Rome') AND NOT name LIKE 'A%'") +people.update({"city": "Oslo"}, where="note IS NULL") +people.count(where="age BETWEEN 20 AND 30") +``` + +```text +python3 -m minidb.cli --db people.json select people --where "age > 30 OR city = 'Rome'" --order-by age +python3 -m minidb.cli --db people.json update people --where "city IS NULL" city=Unknown +python3 -m minidb.cli --db people.json delete people --where "age < 18" +``` + +* Operators: `= != <> < <= > >=`, `IN (...)`, `NOT IN`, `BETWEEN a AND b`, `LIKE` / `ILIKE` with `%` and `_`, `IS NULL`, `IS NOT NULL`. +* Precedence: `NOT` binds tighter than `AND`, which binds tighter than `OR`; parentheses group. +* Literals: integers, floats, `TRUE` / `FALSE`, `NULL` and single-quoted strings (`''` for a quote). Identifiers are column names. +* Comparisons with NULL are unknown and unknown rows are not selected; use `IS NULL`. +* Comparing a string with a number raises `QueryTypeError` when the first offending row is evaluated; an unknown column raises + `QueryNameError` and a malformed expression `QuerySyntaxError` (with the 0-based `position`) before any row is examined. +* `update` and `delete` on the command line take either `--id N` or `--where EXPR`. diff --git a/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/cli.py b/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/cli.py new file mode 100644 index 00000000..28a3ef8c --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/cli.py @@ -0,0 +1,130 @@ +"""Command line interface: ``python3 -m minidb.cli --db FILE COMMAND ...``.""" + +from __future__ import annotations + +import argparse +import sys +from typing import Any, Dict, List, Optional, Sequence, TextIO + +from .csvio import export_csv, import_csv, write_csv +from .errors import MiniDBError, SchemaError +from .schema import Column, Schema, parse_text +from .storage import JsonFileStorage +from .table import Database, Table + + +def parse_column_spec(spec: str) -> Column: + """``name:type`` or ``name:type:required`` (required columns may not be NULL).""" + parts = spec.split(":") + if len(parts) not in (2, 3) or (len(parts) == 3 and parts[2] != "required"): + raise SchemaError("bad column spec %r, expected name:type[:required]" % spec) + return Column(parts[0], parts[1], nullable=len(parts) == 2) + + +def parse_assignments(schema: Schema, items: Sequence[str]) -> Dict[str, Any]: + """Turn ``['name=Ann', 'age=31']`` into typed values; ``age=`` sets NULL.""" + values: Dict[str, Any] = {} + for item in items: + name, separator, text = item.partition("=") + if not separator: + raise SchemaError("expected column=value, got %r" % item) + values[name] = parse_text(schema.column(name), text) + return values + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="minidb", description="Work with a minidb JSON database file.") + parser.add_argument("--db", required=True, help="path of the database file (created on first write)") + commands = parser.add_subparsers(dest="command", required=True) + + create = commands.add_parser("create", help="create a table") + create.add_argument("table") + create.add_argument("columns", nargs="+", metavar="name:type[:required]") + + insert = commands.add_parser("insert", help="insert one row and print its id") + insert.add_argument("table") + insert.add_argument("assignments", nargs="+", metavar="column=value") + + select = commands.add_parser("select", help="print rows as CSV") + select.add_argument("table") + select.add_argument("--columns", help="comma separated column names (default: all)") + select.add_argument("--order-by", dest="order_by", help="column to sort by") + select.add_argument("--desc", action="store_true", help="sort descending") + select.add_argument("--limit", type=int) + select.add_argument("--where", help="only rows for which this expression is true (see SPEC.md)") + + update = commands.add_parser("update", help="change the row with the given id") + update.add_argument("table") + update_filter = update.add_mutually_exclusive_group(required=True) + update_filter.add_argument("--id", type=int, dest="row_id") + update_filter.add_argument("--where", help="update the rows for which this expression is true") + update.add_argument("assignments", nargs="+", metavar="column=value") + + delete = commands.add_parser("delete", help="delete the row with the given id") + delete.add_argument("table") + delete_filter = delete.add_mutually_exclusive_group(required=True) + delete_filter.add_argument("--id", type=int, dest="row_id") + delete_filter.add_argument("--where", help="delete the rows for which this expression is true") + + load = commands.add_parser("import-csv", help="append the rows of a CSV file") + load.add_argument("table") + load.add_argument("file") + + dump = commands.add_parser("export-csv", help="write a table to a CSV file") + dump.add_argument("table") + dump.add_argument("file") + return parser + + +def _row_filter(args: argparse.Namespace): + """The ``where`` argument for the table methods: the query text, or a test for one id.""" + if args.where is not None: + return args.where + row_id = args.row_id + return lambda row: row["id"] == row_id + + +def run(args: argparse.Namespace, db: Database, out: TextIO) -> bool: + """Execute one command; returns True when the database must be saved.""" + if args.command == "create": + db.create_table(args.table, [parse_column_spec(spec) for spec in args.columns]) + return True + table: Table = db.table(args.table) + if args.command == "insert": + print(table.insert(**parse_assignments(table.schema, args.assignments)), file=out) + return True + if args.command == "select": + names: Optional[List[str]] = args.columns.split(",") if args.columns else None + rows = table.select(where=args.where, columns=names, order_by=args.order_by, descending=args.desc, limit=args.limit) + write_csv(rows, names or table.schema.names(), out) + return False + if args.command == "update": + changed = table.update(parse_assignments(table.schema, args.assignments), where=_row_filter(args)) + print("updated %d" % changed, file=out) + return True + if args.command == "delete": + removed = table.delete(where=_row_filter(args)) + print("deleted %d" % removed, file=out) + return True + if args.command == "import-csv": + print("imported %d" % import_csv(table, args.file), file=out) + return True + print("exported %d" % export_csv(table, args.file), file=out) + return False + + +def main(argv: Optional[Sequence[str]] = None, out: Optional[TextIO] = None) -> int: + out = out if out is not None else sys.stdout + args = build_parser().parse_args(argv) + try: + db = Database(JsonFileStorage(args.db)) + if run(args, db, out): + db.save() + except (MiniDBError, OSError) as exc: + print("error: %s" % exc, file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/query.py b/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/query.py new file mode 100644 index 00000000..ecba1f4a --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/query.py @@ -0,0 +1,387 @@ +"""The textual ``where`` language described in SPEC.md. + +``compile_where(text, columns)`` parses an expression once and returns a predicate for rows. +Evaluation uses three truth values: ``True``, ``False`` and ``None`` (UNKNOWN). +""" + +from __future__ import annotations + +import operator +import re +from functools import lru_cache +from typing import Any, Callable, Dict, Iterable, List, Mapping, NamedTuple, Optional, Tuple + +from .errors import MiniDBError + +Row = Mapping[str, Any] +Node = Callable[[Row], Optional[bool]] +Operand = Callable[[Row], Any] + + +class QueryError(MiniDBError): + """Base class of errors in ``where`` expressions.""" + + +class QuerySyntaxError(QueryError): + def __init__(self, message: str, position: int) -> None: + super().__init__("%s at position %d" % (message, position)) + self.message = message + self.position = position + + +class QueryNameError(QueryError): + def __init__(self, name: str, position: int) -> None: + super().__init__("unknown column %s at position %d" % (name, position)) + self.name = name + self.position = position + + +class QueryTypeError(QueryError): + """Two values cannot be compared or used in this way.""" + + +KEYWORDS = frozenset({"AND", "OR", "NOT", "IN", "BETWEEN", "LIKE", "ILIKE", "IS", "NULL", "TRUE", "FALSE"}) +_LETTERS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_") +_DIGITS = frozenset("0123456789") +_NAME_CHARS = _LETTERS | _DIGITS +_COMPARE = { + "=": operator.eq, + "!=": operator.ne, + "<>": operator.ne, + "<": operator.lt, + "<=": operator.le, + ">": operator.gt, + ">=": operator.ge, +} + + +class Token(NamedTuple): + kind: str # NUMBER STRING IDENT KEYWORD OP LPAREN RPAREN COMMA EOF + value: Any + position: int + + +def tokenize(text: str) -> List[Token]: + tokens: List[Token] = [] + i, n = 0, len(text) + while i < n: + ch = text[i] + if ch in " \t\r\n": + i += 1 + elif ch == "'": + start = i + i += 1 + chars: List[str] = [] + while True: + if i >= n: + raise QuerySyntaxError("unterminated string", start) + if text[i] == "'": + if text[i + 1:i + 2] == "'": + chars.append("'") + i += 2 + continue + i += 1 + break + chars.append(text[i]) + i += 1 + tokens.append(Token("STRING", "".join(chars), start)) + elif ch in _DIGITS or (ch in "+-" and text[i + 1:i + 2] in _DIGITS and i + 1 < n): + start = i + i += 1 + while i < n and text[i] in _DIGITS: + i += 1 + if i + 1 < n and text[i] == "." and text[i + 1] in _DIGITS: + i += 1 + while i < n and text[i] in _DIGITS: + i += 1 + tokens.append(Token("NUMBER", float(text[start:i]), start)) + else: + tokens.append(Token("NUMBER", int(text[start:i]), start)) + elif ch in _LETTERS: + start = i + while i < n and text[i] in _NAME_CHARS: + i += 1 + word = text[start:i] + if word.upper() in KEYWORDS: + tokens.append(Token("KEYWORD", word.upper(), start)) + else: + tokens.append(Token("IDENT", word, start)) + elif text[i:i + 2] in ("<=", ">=", "<>", "!="): + tokens.append(Token("OP", text[i:i + 2], i)) + i += 2 + elif ch in "=<>": + tokens.append(Token("OP", ch, i)) + i += 1 + elif ch == "(": + tokens.append(Token("LPAREN", ch, i)) + i += 1 + elif ch == ")": + tokens.append(Token("RPAREN", ch, i)) + i += 1 + elif ch == ",": + tokens.append(Token("COMMA", ch, i)) + i += 1 + else: + raise QuerySyntaxError("invalid character %r" % ch, i) + tokens.append(Token("EOF", None, n)) + return tokens + + +# -- evaluation helpers ------------------------------------------------------- + + +def _is_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _compare(op: str, a: Any, b: Any) -> Optional[bool]: + if a is None or b is None: + return None + both_numbers = _is_number(a) and _is_number(b) + both_strings = isinstance(a, str) and isinstance(b, str) + both_bools = isinstance(a, bool) and isinstance(b, bool) + if not (both_numbers or both_strings or both_bools): + raise QueryTypeError("cannot compare %s with %s" % (type(a).__name__, type(b).__name__)) + return _COMPARE[op](a, b) + + +@lru_cache(maxsize=256) +def _like_regex(pattern: str) -> "re.Pattern[str]": + parts = [] + for ch in pattern: + parts.append(".*" if ch == "%" else "." if ch == "_" else re.escape(ch)) + return re.compile("".join(parts), re.DOTALL) + + +def _like(a: Any, pattern: Any, ignore_case: bool) -> Optional[bool]: + if a is None or pattern is None: + return None + if not isinstance(a, str) or not isinstance(pattern, str): + raise QueryTypeError("LIKE needs strings, got %s and %s" % (type(a).__name__, type(pattern).__name__)) + if ignore_case: + a, pattern = a.lower(), pattern.lower() + return _like_regex(pattern).fullmatch(a) is not None + + +def _and(left: Node, right: Node) -> Node: + def evaluate(row: Row) -> Optional[bool]: + a = left(row) + if a is False: + return False + b = right(row) + if b is False: + return False + return None if a is None or b is None else True + + return evaluate + + +def _or(left: Node, right: Node) -> Node: + def evaluate(row: Row) -> Optional[bool]: + a = left(row) + if a is True: + return True + b = right(row) + if b is True: + return True + return None if a is None or b is None else False + + return evaluate + + +def _not(inner: Node) -> Node: + def evaluate(row: Row) -> Optional[bool]: + value = inner(row) + return None if value is None else not value + + return evaluate + + +def _constant(value: Any) -> Operand: + return lambda row: value + + +def _column(name: str) -> Operand: + return lambda row: row[name] + + +def _comparison(op: str, left: Operand, right: Operand) -> Node: + return lambda row: _compare(op, left(row), right(row)) + + +def _in_list(operand: Operand, values: List[Any]) -> Node: + def evaluate(row: Row) -> Optional[bool]: + x = operand(row) + unknown = False + for value in values: + result = _compare("=", x, value) + if result is True: + return True + unknown = unknown or result is None + return None if unknown else False + + return evaluate + + +def _bare(operand: Operand) -> Node: + def evaluate(row: Row) -> Optional[bool]: + value = operand(row) + if value is None or isinstance(value, bool): + return value + raise QueryTypeError("%s is not a boolean condition" % type(value).__name__) + + return evaluate + + +def _is_null(operand: Operand) -> Node: + return lambda row: operand(row) is None + + +# -- parser ------------------------------------------------------------------- + + +class _Parser: + def __init__(self, text: str) -> None: + self.text = text + self.tokens = tokenize(text) + self.index = 0 + self.references: List[Tuple[str, int]] = [] + + @property + def current(self) -> Token: + return self.tokens[self.index] + + def advance(self) -> Token: + token = self.tokens[self.index] + if token.kind != "EOF": + self.index += 1 + return token + + def at_keyword(self, *words: str) -> bool: + return self.current.kind == "KEYWORD" and self.current.value in words + + def fail(self) -> QuerySyntaxError: + token = self.current + if token.kind == "EOF": + return QuerySyntaxError("unexpected end of input", len(self.text)) + return QuerySyntaxError("unexpected token", token.position) + + def expect_keyword(self, word: str) -> None: + if not self.at_keyword(word): + raise self.fail() + self.advance() + + def parse(self) -> Node: + node = self.parse_or() + if self.current.kind != "EOF": + raise self.fail() + return node + + def parse_or(self) -> Node: + node = self.parse_and() + while self.at_keyword("OR"): + self.advance() + node = _or(node, self.parse_and()) + return node + + def parse_and(self) -> Node: + node = self.parse_not() + while self.at_keyword("AND"): + self.advance() + node = _and(node, self.parse_not()) + return node + + def parse_not(self) -> Node: + if self.at_keyword("NOT"): + self.advance() + return _not(self.parse_not()) + return self.parse_primary() + + def parse_primary(self) -> Node: + if self.current.kind == "LPAREN": + self.advance() + node = self.parse_or() + if self.current.kind != "RPAREN": + raise self.fail() + self.advance() + return node + return self.parse_predicate() + + def parse_predicate(self) -> Node: + left = self.parse_operand() + token = self.current + if token.kind == "OP": + self.advance() + return _comparison(token.value, left, self.parse_operand()) + if self.at_keyword("IS"): + self.advance() + negate = self.at_keyword("NOT") + if negate: + self.advance() + self.expect_keyword("NULL") + node = _is_null(left) + return _not(node) if negate else node + negate = False + if self.at_keyword("NOT"): + self.advance() + negate = True + if not self.at_keyword("IN", "BETWEEN", "LIKE", "ILIKE"): + raise self.fail() + if self.at_keyword("IN"): + self.advance() + node = _in_list(left, self.parse_literal_list()) + elif self.at_keyword("BETWEEN"): + self.advance() + low = self.parse_operand() + self.expect_keyword("AND") + high = self.parse_operand() + node = _and(_comparison(">=", left, low), _comparison("<=", left, high)) + elif self.at_keyword("LIKE", "ILIKE"): + ignore_case = self.advance().value == "ILIKE" + pattern = self.parse_operand() + node = lambda row, p=pattern, ic=ignore_case: _like(left(row), p(row), ic) + else: + return _bare(left) + return _not(node) if negate else node + + def parse_operand(self) -> Operand: + token = self.current + if token.kind == "IDENT": + self.advance() + self.references.append((token.value, token.position)) + return _column(token.value) + return _constant(self.parse_literal()) + + def parse_literal(self) -> Any: + token = self.current + if token.kind in ("NUMBER", "STRING"): + self.advance() + return token.value + if self.at_keyword("TRUE", "FALSE", "NULL"): + self.advance() + return {"TRUE": True, "FALSE": False, "NULL": None}[token.value] + raise self.fail() + + def parse_literal_list(self) -> List[Any]: + if self.current.kind != "LPAREN": + raise self.fail() + self.advance() + values = [self.parse_literal()] + while self.current.kind == "COMMA": + self.advance() + values.append(self.parse_literal()) + if self.current.kind != "RPAREN": + raise self.fail() + self.advance() + return values + + +def compile_where(text: str, columns: Iterable[str]) -> Callable[[Row], bool]: + """Parse ``text`` and return a predicate that is true for the rows the expression selects.""" + known = set(columns) + parser = _Parser(text) + node = parser.parse() + for name, position in parser.references: + if name not in known: + raise QueryNameError(name, position) + return lambda row: node(row) is True diff --git a/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/table.py b/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/table.py new file mode 100644 index 00000000..cef1afaf --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/table.py @@ -0,0 +1,199 @@ +"""Tables and the database that owns them.""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Union + +from .errors import RowNotFound, SchemaError, TableError +from .index import HashIndex +from .query import compile_where +from .schema import Column, Schema +from .storage import MemoryStorage + +Row = Dict[str, Any] +Predicate = Callable[[Row], Any] +Where = Union[None, str, Predicate] + + +class Table: + """Rows of one schema, kept in insertion order and addressed by integer id.""" + + def __init__(self, name: str, schema: Schema) -> None: + self.name = name + self.schema = schema + self._rows: Dict[int, Row] = {} + self._next_id = 1 + self._indexes: Dict[str, HashIndex] = {} + + def __len__(self) -> int: + return len(self._rows) + + # -- writing --------------------------------------------------------- + + def insert(self, **values: Any) -> int: + """Add a row and return its id.""" + row = self.schema.build_row(values, self._next_id) + self._rows[row["id"]] = row + self._next_id += 1 + for index in self._indexes.values(): + index.add(row) + return row["id"] + + def insert_many(self, rows: Iterable[Mapping[str, Any]]) -> List[int]: + return [self.insert(**row) for row in rows] + + def update(self, values: Mapping[str, Any], where: Where = None) -> int: + """Change the matching rows (all rows without ``where``); returns how many changed.""" + changes = self.schema.coerce_changes(values) + matches = self._matcher(where) + targets = [row for row in self._rows.values() if matches(row)] + for row in targets: + for index in self._indexes.values(): + index.remove(row) + row.update(changes) + for index in self._indexes.values(): + index.add(row) + return len(targets) + + def delete(self, where: Where = None) -> int: + """Remove the matching rows (all rows without ``where``); returns how many were removed.""" + matches = self._matcher(where) + targets = [row for row in self._rows.values() if matches(row)] + for row in targets: + del self._rows[row["id"]] + for index in self._indexes.values(): + index.remove(row) + return len(targets) + + # -- reading --------------------------------------------------------- + + def get(self, row_id: int) -> Row: + try: + return dict(self._rows[row_id]) + except KeyError: + raise RowNotFound("no row with id %r in table %s" % (row_id, self.name)) from None + + def find(self, column: str, value: Any) -> List[Row]: + """Rows whose ``column`` equals ``value``; uses the index when there is one.""" + self.schema.column(column) + index = self._indexes.get(column) + if index is not None: + return [dict(self._rows[i]) for i in index.lookup(value)] + return [dict(r) for r in self._rows.values() if r[column] is not None and r[column] == value] + + def select( + self, + where: Where = None, + columns: Optional[Sequence[str]] = None, + order_by: Optional[str] = None, + descending: bool = False, + limit: Optional[int] = None, + ) -> List[Row]: + """Rows selected by ``where`` (a callable or a query string), optionally sorted, limited and projected. + + Rows whose ``order_by`` value is NULL always come last. + """ + matches = self._matcher(where) + rows = [row for row in self._rows.values() if matches(row)] + if order_by is not None: + rows = self._ordered(rows, order_by, descending) + if limit is not None: + rows = rows[:limit] + return [self._project(row, columns) for row in rows] + + def count(self, where: Where = None) -> int: + matches = self._matcher(where) + return sum(1 for row in self._rows.values() if matches(row)) + + # -- indexes --------------------------------------------------------- + + def create_index(self, column: str) -> None: + self.schema.column(column) + if column in self._indexes: + raise TableError("column %s is already indexed" % column) + index = HashIndex(column) + index.rebuild(self._rows.values()) + self._indexes[column] = index + + def indexed_columns(self) -> List[str]: + return sorted(self._indexes) + + # -- internals ------------------------------------------------------- + + def _matcher(self, where: Where) -> Predicate: + if where is None: + return lambda row: True + if isinstance(where, str): + return compile_where(where, self.schema.names()) + if callable(where): + return where + raise TypeError("where must be a string, a callable or None, not %s" % type(where).__name__) + + def _ordered(self, rows: List[Row], order_by: str, descending: bool) -> List[Row]: + self.schema.column(order_by) + present = [row for row in rows if row[order_by] is not None] + missing = [row for row in rows if row[order_by] is None] + present.sort(key=lambda row: row[order_by], reverse=descending) + return present + missing + + def _project(self, row: Row, columns: Optional[Sequence[str]]) -> Row: + if columns is None: + return dict(row) + for name in columns: + self.schema.column(name) + return {name: row[name] for name in columns} + + # -- persistence ----------------------------------------------------- + + def to_dict(self) -> Dict[str, Any]: + return { + "schema": self.schema.to_dict(), + "next_id": self._next_id, + "indexes": self.indexed_columns(), + "rows": [dict(row) for row in self._rows.values()], + } + + @classmethod + def from_dict(cls, name: str, spec: Mapping[str, Any]) -> "Table": + table = cls(name, Schema.from_dict(spec["schema"])) + for row in spec["rows"]: + table._rows[row["id"]] = dict(row) + table._next_id = spec["next_id"] + for column in spec.get("indexes", []): + table.create_index(column) + return table + + +class Database: + """A named collection of tables backed by a storage object.""" + + def __init__(self, storage: Optional[Any] = None) -> None: + self.storage = storage if storage is not None else MemoryStorage() + self._tables: Dict[str, Table] = {} + data = self.storage.load() + if data: + for name, spec in data["tables"].items(): + self._tables[name] = Table.from_dict(name, spec) + + def create_table(self, name: str, columns: Iterable[Column]) -> Table: + if name in self._tables: + raise TableError("table already exists: %s" % name) + table = Table(name, Schema(columns)) + self._tables[name] = table + return table + + def table(self, name: str) -> Table: + try: + return self._tables[name] + except KeyError: + raise TableError("no such table: %s" % name) from None + + def drop_table(self, name: str) -> None: + self.table(name) + del self._tables[name] + + def table_names(self) -> List[str]: + return sorted(self._tables) + + def save(self) -> None: + self.storage.save({"version": 1, "tables": {n: t.to_dict() for n, t in self._tables.items()}}) diff --git a/scripts/e2e/codex/tasks/feature-query/reference/overlay/tests/test_query.py b/scripts/e2e/codex/tasks/feature-query/reference/overlay/tests/test_query.py new file mode 100644 index 00000000..a875b82f --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/reference/overlay/tests/test_query.py @@ -0,0 +1,208 @@ +import unittest + +from minidb import Column, Database +from minidb.errors import MiniDBError +from minidb.query import ( + QueryError, + QueryNameError, + QuerySyntaxError, + QueryTypeError, + compile_where, +) + +ROWS = [ + {"name": "Ann", "age": 31, "city": "Berlin", "active": True, "note": "likes tea"}, + {"name": "Bob", "age": 25, "city": "Paris", "active": False, "note": None}, + {"name": "Cid", "age": None, "city": "Berlin", "active": True, "note": "50% done"}, + {"name": "Dee", "age": 40, "city": None, "active": None, "note": "a_b"}, + {"name": "O'Neil", "age": 19, "city": "Rome", "active": False, "note": ""}, +] + + +def make_table(): + db = Database() + table = db.create_table("people", [ + Column("name"), Column("age", "int"), Column("city"), Column("active", "bool"), Column("note"), + ]) + table.insert_many(ROWS) + return table + + +class QueryTestCase(unittest.TestCase): + def setUp(self): + self.table = make_table() + + def ids(self, where): + return [row["id"] for row in self.table.select(where=where)] + + +class ComparisonTests(QueryTestCase): + def test_equality_and_inequality(self): + self.assertEqual(self.ids("city = 'Berlin'"), [1, 3]) + self.assertEqual(self.ids("city != 'Berlin'"), [2, 5]) + self.assertEqual(self.ids("city <> 'Berlin'"), [2, 5]) + + def test_ordering_operators(self): + self.assertEqual(self.ids("age > 31"), [4]) + self.assertEqual(self.ids("age >= 31"), [1, 4]) + self.assertEqual(self.ids("age < 25"), [5]) + self.assertEqual(self.ids("age <= 25"), [2, 5]) + + def test_int_and_float_compare_numerically(self): + self.assertEqual(self.ids("age = 31.0"), [1]) + self.assertEqual(self.ids("age > 30.5"), [1, 4]) + + def test_negative_and_signed_numbers(self): + self.assertEqual(self.ids("age > -1"), [1, 2, 4, 5]) + self.assertEqual(self.ids("age = +25"), [2]) + + def test_booleans(self): + self.assertEqual(self.ids("active = TRUE"), [1, 3]) + self.assertEqual(self.ids("active"), [1, 3]) + self.assertEqual(self.ids("NOT active"), [2, 5]) + + def test_string_escape(self): + self.assertEqual(self.ids("name = 'O''Neil'"), [5]) + + +class LogicTests(QueryTestCase): + def test_and_binds_tighter_than_or(self): + self.assertEqual(self.ids("age = 25 OR age = 31 AND city = 'Paris'"), [2]) + self.assertEqual(self.ids("(age = 25 OR age = 31) AND city = 'Paris'"), [2]) + self.assertEqual(self.ids("age = 40 OR age = 31 AND city = 'Berlin'"), [1, 4]) + + def test_not_binds_tighter_than_and(self): + self.assertEqual(self.ids("NOT age > 30 AND active"), []) + self.assertEqual(self.ids("NOT age > 30 AND NOT active"), [2, 5]) + + def test_keywords_in_any_case(self): + self.assertEqual(self.ids("age > 30 and city = 'Berlin' or name = 'Bob'"), [1, 2]) + + def test_unknown_is_not_selected_even_when_negated(self): + self.assertEqual(self.ids("age = NULL"), []) + self.assertEqual(self.ids("NOT (age = 31)"), [2, 4, 5]) + self.assertEqual(self.ids("age != 31"), [2, 4, 5]) + + def test_unknown_or_true_is_true(self): + self.assertEqual(self.ids("age > 100 OR active"), [1, 3]) + + +class PredicateTests(QueryTestCase): + def test_in_and_not_in(self): + self.assertEqual(self.ids("city IN ('Paris', 'Rome')"), [2, 5]) + self.assertEqual(self.ids("city NOT IN ('Paris', 'Rome')"), [1, 3]) + self.assertEqual(self.ids("age NOT IN (25, NULL)"), []) + + def test_between(self): + self.assertEqual(self.ids("age BETWEEN 25 AND 31"), [1, 2]) + self.assertEqual(self.ids("age NOT BETWEEN 25 AND 31"), [4, 5]) + self.assertEqual(self.ids("age BETWEEN 20 AND 40 AND active"), [1]) + + def test_like_wildcards(self): + self.assertEqual(self.ids("name LIKE 'B%'"), [2]) + self.assertEqual(self.ids("name LIKE '_ee'"), [4]) + self.assertEqual(self.ids("note LIKE '50%'"), [3]) + self.assertEqual(self.ids("note LIKE 'a_b'"), [4]) + self.assertEqual(self.ids("note LIKE ''"), [5]) + + def test_like_is_case_sensitive_and_ilike_is_not(self): + self.assertEqual(self.ids("name LIKE 'ann'"), []) + self.assertEqual(self.ids("name ILIKE 'ann'"), [1]) + self.assertEqual(self.ids("note NOT ILIKE '%TEA%'"), [3, 4, 5]) + + def test_like_does_not_use_regular_expressions(self): + self.assertEqual(self.ids("name LIKE 'A.n'"), []) + self.assertEqual(self.ids("name LIKE '[A-C]%'"), []) + + def test_is_null(self): + self.assertEqual(self.ids("age IS NULL"), [3]) + self.assertEqual(self.ids("note IS NOT NULL"), [1, 3, 4, 5]) + self.assertEqual(self.ids("city IS NULL OR note IS NULL"), [2, 4]) + + +class SyntaxErrorTests(QueryTestCase): + def position(self, text): + with self.assertRaises(QuerySyntaxError) as caught: + compile_where(text, self.table.schema.names()) + return caught.exception.position + + def test_end_of_input(self): + self.assertEqual(self.position(""), 0) + self.assertEqual(self.position("age >"), 5) + self.assertEqual(self.position("(age = 1"), 8) + + def test_unexpected_tokens(self): + self.assertEqual(self.position("age = = 1"), 6) + self.assertEqual(self.position("age = 1)"), 7) + self.assertEqual(self.position("age IN ()"), 8) + self.assertEqual(self.position("age BETWEEN 1 2"), 14) + + def test_lexical_errors(self): + self.assertEqual(self.position("name = 'abc"), 7) + self.assertEqual(self.position("age = 1 # note"), 8) + + def test_message_ends_with_position(self): + with self.assertRaises(QuerySyntaxError) as caught: + compile_where("age = 1 name", ["age", "name"]) + self.assertTrue(str(caught.exception).endswith("at position 8")) + + +class NameAndTypeErrorTests(QueryTestCase): + def test_unknown_column_is_found_before_rows_are_read(self): + empty = make_table() + empty.delete() + with self.assertRaises(QueryNameError) as caught: + empty.select(where="age > 1 AND agee = 2") + self.assertEqual((caught.exception.name, caught.exception.position), ("agee", 12)) + + def test_syntax_error_wins_over_name_error(self): + with self.assertRaises(QuerySyntaxError): + self.table.select(where="nope = ") + + def test_type_errors(self): + for text in ("name = 5", "age = 'x'", "active = 1", "age", "name LIKE 5", "age LIKE 'x'"): + with self.assertRaises(QueryTypeError, msg=text): + self.table.select(where=text) + + def test_type_error_only_when_a_row_gets_there(self): + self.assertEqual(self.ids("id < 0 AND name = 5"), []) + self.assertEqual(self.ids("id > 0 OR name = 5"), [1, 2, 3, 4, 5]) + only_nulls = Database().create_table("t", [Column("age", "int")]) + only_nulls.insert(age=None) + self.assertEqual(only_nulls.select(where="age = 'x'"), []) + + def test_class_hierarchy(self): + for cls in (QuerySyntaxError, QueryNameError, QueryTypeError): + self.assertTrue(issubclass(cls, QueryError)) + self.assertTrue(issubclass(QueryError, MiniDBError)) + + +class TableIntegrationTests(QueryTestCase): + def test_callable_where_still_works(self): + self.assertEqual([r["id"] for r in self.table.select(where=lambda row: row["age"] == 25)], [2]) + + def test_string_where_with_options(self): + rows = self.table.select(where="age IS NOT NULL", order_by="age", descending=True, limit=2, columns=["name"]) + self.assertEqual(rows, [{"name": "Dee"}, {"name": "Ann"}]) + + def test_count_update_delete(self): + self.assertEqual(self.table.count(where="city = 'Berlin'"), 2) + self.assertEqual(self.table.update({"city": "Oslo"}, where="city = 'Berlin'"), 2) + self.assertEqual(self.ids("city = 'Oslo'"), [1, 3]) + self.assertEqual(self.table.delete(where="age IS NULL"), 1) + self.assertEqual(len(self.table), 4) + + def test_other_types_are_still_rejected(self): + with self.assertRaises(TypeError): + self.table.select(where=42) + + def test_predicate_can_be_reused(self): + predicate = compile_where("age > 30", ["id", "age"]) + self.assertTrue(predicate({"id": 1, "age": 31})) + self.assertFalse(predicate({"id": 2, "age": 30})) + self.assertFalse(predicate({"id": 3, "age": None})) + self.assertTrue(predicate({"id": 4, "age": 99})) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/seed/README.md b/scripts/e2e/codex/tasks/feature-query/seed/README.md new file mode 100644 index 00000000..6e24732f --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/README.md @@ -0,0 +1,57 @@ +# minidb + +A tiny in-process table store with JSON persistence. Pure Python 3, standard library only. + +## Library + +```python +from minidb import Column, Database, JsonFileStorage + +db = Database(JsonFileStorage("people.json")) # or Database() for an in-memory database +people = db.create_table("people", [ + Column("name", "str", nullable=False), + Column("age", "int"), + Column("city", "str"), +]) +person_id = people.insert(name="Ann", age=31, city="Berlin") +db.save() + +people.select(where=lambda row: row["age"] is not None and row["age"] > 30, order_by="name", limit=10) +people.update({"city": "Rome"}, where=lambda row: row["city"] == "Berlin") +people.delete(where=lambda row: row["age"] is None) +people.count() +``` + +* Column types are `int`, `float`, `str` and `bool`. Every table has an integer `id` column that is assigned automatically. +* `select(where=None, columns=None, order_by=None, descending=False, limit=None)` returns copies of the rows as dictionaries, in insertion order + unless `order_by` is given. Rows with NULL in the `order_by` column come last. +* `where` is a callable that receives the row dictionary; `None` means every row. +* `Table.create_index(column)` adds a hash index that speeds up `Table.find(column, value)`. +* Column names must be identifiers and must not be one of the reserved words `AND OR NOT IN BETWEEN LIKE ILIKE IS NULL TRUE FALSE`. + +## Command line + +```text +python3 -m minidb.cli --db people.json create people name:str:required age:int city:str +python3 -m minidb.cli --db people.json insert people name=Ann age=31 city=Berlin +python3 -m minidb.cli --db people.json select people --columns id,name --order-by age --desc --limit 5 +python3 -m minidb.cli --db people.json update people --id 1 city=Rome +python3 -m minidb.cli --db people.json delete people --id 1 +python3 -m minidb.cli --db people.json import-csv people people.csv +python3 -m minidb.cli --db people.json export-csv people out.csv +``` + +* `select` prints CSV (header line, then one line per row; NULL is an empty field, booleans are `true` / `false`). +* `column=` with nothing after the equals sign sets NULL. +* `update` and `delete` print `updated N` / `deleted N`. +* Errors print `error: ...` on standard error and the exit status is 2. + +## Tests + +```text +python3 -m unittest discover -s tests +``` + +## Query language + +The textual `where` language is specified in `SPEC.md` and is not implemented yet. diff --git a/scripts/e2e/codex/tasks/feature-query/seed/SPEC.md b/scripts/e2e/codex/tasks/feature-query/seed/SPEC.md new file mode 100644 index 00000000..5417748a --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/SPEC.md @@ -0,0 +1,180 @@ +# Specification: the `where` query language + +This document defines the textual `where` expressions that `minidb` accepts in addition to Python callables. +It is the single source of truth: an implementation that follows it exactly is correct. + +## 1. Where it applies + +* `minidb/query.py` exposes `compile_where(text, columns)`, where `text` is the expression and `columns` is an iterable of the table's + column names (including `id`). It returns a predicate `predicate(row) -> bool` for a row given as a `dict`. +* The predicate returns `True` when the expression evaluates to TRUE for the row and `False` when it evaluates to FALSE or UNKNOWN. + (UNKNOWN is the third truth value of SQL-style logic, see section 5; unknown rows are never selected.) +* `Table.select`, `Table.update`, `Table.delete` and `Table.count` accept `where` either as a callable (unchanged behaviour), as `None` + (all rows, unchanged), or as a `str`, which is compiled with `compile_where` using the table's column names before any row is examined. + An empty or blank string is an expression like any other and is a syntax error (section 3.4). Any other type raises `TypeError` as before. +* The command line tool accepts `--where EXPRESSION` for `select`, `update` and `delete` (section 8). + +## 2. Lexical structure + +The text is first split into tokens. Characters are counted from 0; every position in this document is an index into the original text, +including leading whitespace. + +* **Whitespace** (space, tab, carriage return, line feed) separates tokens and is otherwise ignored. +* **Keywords**, matched case-insensitively and only as whole words: `AND OR NOT IN BETWEEN LIKE ILIKE IS NULL TRUE FALSE`. +* **Identifiers**: an ASCII letter or underscore followed by ASCII letters, digits or underscores, that is not a keyword. A word is read as + far as these characters go, so `note` and `android` are identifiers, not `NOT` or `AND` followed by something. Identifiers are case-sensitive + and name columns. +* **Numbers**: an optional sign (`+` or `-`) written directly in front of the digits, then one or more digits, optionally followed by a dot and + one or more digits. Without a dot the number is an integer, with a dot it is a float. Leading zeros are allowed. `-5` is one token. + A sign that is not directly followed by a digit is an invalid character. There is no arithmetic, so `5-3` is the number `5` followed by + the number `-3` (a syntax error, section 3.4). +* **Strings**: enclosed in single quotes. A quote inside a string is written twice (`'it''s'` is `it's`). There are no other escape + sequences, a backslash is an ordinary character, and a string may contain any character including newlines. +* **Operators and punctuation**: `=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`, `(`, `)`, `,`. The two-character operators win over their one-character + prefixes (`<=` is one token, not `<` then `=`). `!=` and `<>` mean the same thing. +* Any other character (including a `!` that is not followed by `=`, a `.` that is not inside a number, and non-ASCII characters outside + strings) is invalid. + +Tokenisation of the whole text happens before parsing, so a lexical error (invalid character, unterminated string) is reported in +preference to any syntax error, wherever either is. + +## 3. Grammar + +```text +expression := or_expr +or_expr := and_expr { OR and_expr } +and_expr := not_expr { AND not_expr } +not_expr := NOT not_expr | primary +primary := '(' expression ')' | predicate +predicate := operand [ suffix ] +suffix := cmp_op operand + | [ NOT ] IN '(' literal { ',' literal } ')' + | [ NOT ] BETWEEN operand AND operand + | [ NOT ] ( LIKE | ILIKE ) operand + | IS [ NOT ] NULL +cmp_op := '=' | '!=' | '<>' | '<' | '<=' | '>' | '>=' +operand := IDENT | literal +literal := NUMBER | STRING | TRUE | FALSE | NULL +``` + +### 3.1 Precedence and associativity + +From the tightest to the loosest: the predicate forms (comparison, `IN`, `BETWEEN`, `LIKE`, `IS NULL`), then `NOT`, then `AND`, then `OR`. +`AND` and `OR` are left-associative. Parentheses group. `NOT age > 30` is `NOT (age > 30)`. The `AND` inside `BETWEEN a AND b` belongs to the +`BETWEEN`; in `x BETWEEN 1 AND 5 AND y = 2` the second `AND` is the logical one. + +### 3.2 Meaning of each form + +Let `x`, `a`, `b` be operands and `p`, `q` expressions. The forms are defined by these equivalences (evaluation order and short-circuiting +follow section 5): + +* `x NOT IN (a, b, c)` is `NOT (x IN (a, b, c))`, and `x IN (a, b, c)` is `x = a OR x = b OR x = c`, evaluated left to right. +* `x BETWEEN a AND b` is `x >= a AND x <= b` (no swapping of the bounds: `x BETWEEN 5 AND 1` is never true), and `x NOT BETWEEN a AND b` is + `NOT (x BETWEEN a AND b)`. +* `x NOT LIKE a` is `NOT (x LIKE a)`; `x NOT ILIKE a` is `NOT (x ILIKE a)`. +* `x IS NOT NULL` is `NOT (x IS NULL)`. +* A *bare operand* used as a condition (a predicate without a suffix) is true or false when it is a boolean, and unknown when it is NULL. + +### 3.3 Not supported + +Arithmetic, function calls, quoted identifiers, comments, subqueries and escape characters in `LIKE` patterns do not exist. A column whose name is +a keyword cannot be referenced (such names are rejected when a column is created). + +### 3.4 Syntax errors + +A syntax error is a `QuerySyntaxError` with an integer attribute `position`. The parser reads tokens from left to right and reports the first +token that cannot continue a valid expression, using the grammar above: + +* if that token exists, `position` is the index of its first character; +* if the text ends too early (including an empty or blank text), `position` is `len(text)`; +* a token left over after a complete expression (for example `age = 1 name = 2`, or a stray `)`) is reported at that token; +* an unterminated string is reported at its opening quote, an invalid character at that character. + +`str(error)` is a short description followed by ` at position N`, for example `unexpected token at position 8`. + +## 4. Values and types + +A row value is an `int`, `float`, `str`, `bool` or `None` (NULL). Literals have the obvious types; `TRUE` and `FALSE` are booleans. For the +purposes of this language `bool` is **not** a number. + +### 4.1 Comparison (`=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`) + +1. If either operand is NULL the result is UNKNOWN. No type check is made. +2. Two numbers (`int` or `float`) compare by numeric value, so `30 = 30.0` is TRUE. +3. Two strings compare by code point order, case-sensitively (`'B' < 'a'`, `'Dave' > 'D'`). +4. Two booleans compare with `FALSE < TRUE`, all six operators allowed. +5. Any other combination (string with number, boolean with number, boolean with string) raises `QueryTypeError`, whatever the operator. + +### 4.2 `LIKE` and `ILIKE` + +`x LIKE p` compares the string `x` with the pattern `p`. In the pattern `%` matches any sequence of characters (including none), `_` matches exactly +one character (any character, including a newline), and every other character, including regular-expression characters such as `.` and `[`, +matches only itself. The pattern must match the whole string. `LIKE` is case-sensitive; `ILIKE` compares after converting both strings with +`str.lower()`. If either side is NULL the result is UNKNOWN (checked first); otherwise both sides must be strings, else `QueryTypeError`. +Either side may be a column or a literal. + +### 4.3 `IS NULL` + +`x IS NULL` is TRUE when `x` is NULL and FALSE otherwise; it is never UNKNOWN and never a type error. + +### 4.4 Bare operands + +A bare operand that is a boolean gives TRUE or FALSE, NULL gives UNKNOWN, and any other value (number, string) raises `QueryTypeError`. + +### 4.5 When type errors happen + +A `QueryTypeError` is raised by the predicate, when it is called on the first row for which evaluation (section 5) reaches a forbidden +combination. It is never raised while compiling, and never for rows where the offending part is not evaluated (NULL operands, short-circuiting). +A query over a table with no rows, or whose rows never reach the forbidden combination, never raises it. + +## 5. Three-valued logic and evaluation order + +Truth values are TRUE, FALSE, UNKNOWN. + +* `NOT`: TRUE becomes FALSE, FALSE becomes TRUE, UNKNOWN stays UNKNOWN. +* `p AND q`: evaluate `p` first. If it is FALSE the result is FALSE and `q` is **not evaluated**. Otherwise evaluate `q`: the result is FALSE if + `q` is FALSE; else UNKNOWN if either operand is UNKNOWN; else TRUE. +* `p OR q`: evaluate `p` first. If it is TRUE the result is TRUE and `q` is **not evaluated**. Otherwise evaluate `q`: the result is TRUE if `q` is + TRUE; else UNKNOWN if either operand is UNKNOWN; else FALSE. +* UNKNOWN on the left never short-circuits. Chains evaluate left to right. + +Consequences worth remembering: `x = NULL` is UNKNOWN, never TRUE, for every `x`; `x NOT IN (1, NULL)` is never TRUE; `NOT (x = 1)` is not selected +for a row whose `x` is NULL. + +## 6. Names + +Every identifier must be a column name of the table. Unknown identifiers raise `QueryNameError` while compiling, before any row is examined, even +on an empty table. The error has the attributes `name` (the identifier) and `position` (index of its first occurrence in the text, scanning left to +right). Name checking happens after parsing succeeded: a text with a syntax error raises `QuerySyntaxError` even if it also contains unknown +identifiers. + +## 7. Error classes + +All in `minidb/query.py`: + +```text +MiniDBError (minidb/errors.py) + QueryError + QuerySyntaxError attribute: position + QueryNameError attributes: name, position + QueryTypeError +``` + +## 8. Command line + +`select`, `update` and `delete` take `--where EXPRESSION`. For `update` and `delete` the options `--id N` and `--where EXPRESSION` are mutually +exclusive and exactly one of them is required. `select` without `--where` prints all rows as before; with it, only the rows for which the expression +is TRUE (in id order unless `--order-by` is given). `update` and `delete` print `updated N` / `deleted N` with the number of affected rows. +A query error (`QueryError`) is reported like every other `MiniDBError`: `error: ` on standard error and exit status 2. + +## 9. Examples + +| Expression | Selects | +| --- | --- | +| `age >= 18 AND city = 'Berlin'` | adults in Berlin | +| `name LIKE 'A%' OR name ILIKE '%son'` | names starting with `A` or ending with `son` in any case | +| `age BETWEEN 20 AND 30` | `20 <= age <= 30`; rows with NULL age are not selected | +| `city IN ('Rome', 'Paris') AND NOT active` | `active` is a boolean column | +| `note IS NULL OR note = ''` | missing or empty notes | +| `age NOT IN (25, 30)` | NULL ages are not selected either | +| `name = 'O''Brien'` | quote escaping | diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/__init__.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/__init__.py new file mode 100644 index 00000000..ec37da90 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/__init__.py @@ -0,0 +1,19 @@ +"""minidb: a tiny in-process table store with JSON persistence.""" + +from .errors import MiniDBError, RowNotFound, SchemaError, TableError +from .schema import Column, Schema +from .storage import JsonFileStorage, MemoryStorage +from .table import Database, Table + +__all__ = [ + "Column", + "Database", + "JsonFileStorage", + "MemoryStorage", + "MiniDBError", + "RowNotFound", + "Schema", + "SchemaError", + "Table", + "TableError", +] diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/cli.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/cli.py new file mode 100644 index 00000000..bf0c8119 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/cli.py @@ -0,0 +1,121 @@ +"""Command line interface: ``python3 -m minidb.cli --db FILE COMMAND ...``.""" + +from __future__ import annotations + +import argparse +import sys +from typing import Any, Dict, List, Optional, Sequence, TextIO + +from .csvio import export_csv, import_csv, write_csv +from .errors import MiniDBError, SchemaError +from .schema import Column, Schema, parse_text +from .storage import JsonFileStorage +from .table import Database, Table + + +def parse_column_spec(spec: str) -> Column: + """``name:type`` or ``name:type:required`` (required columns may not be NULL).""" + parts = spec.split(":") + if len(parts) not in (2, 3) or (len(parts) == 3 and parts[2] != "required"): + raise SchemaError("bad column spec %r, expected name:type[:required]" % spec) + return Column(parts[0], parts[1], nullable=len(parts) == 2) + + +def parse_assignments(schema: Schema, items: Sequence[str]) -> Dict[str, Any]: + """Turn ``['name=Ann', 'age=31']`` into typed values; ``age=`` sets NULL.""" + values: Dict[str, Any] = {} + for item in items: + name, separator, text = item.partition("=") + if not separator: + raise SchemaError("expected column=value, got %r" % item) + values[name] = parse_text(schema.column(name), text) + return values + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="minidb", description="Work with a minidb JSON database file.") + parser.add_argument("--db", required=True, help="path of the database file (created on first write)") + commands = parser.add_subparsers(dest="command", required=True) + + create = commands.add_parser("create", help="create a table") + create.add_argument("table") + create.add_argument("columns", nargs="+", metavar="name:type[:required]") + + insert = commands.add_parser("insert", help="insert one row and print its id") + insert.add_argument("table") + insert.add_argument("assignments", nargs="+", metavar="column=value") + + select = commands.add_parser("select", help="print rows as CSV") + select.add_argument("table") + select.add_argument("--columns", help="comma separated column names (default: all)") + select.add_argument("--order-by", dest="order_by", help="column to sort by") + select.add_argument("--desc", action="store_true", help="sort descending") + select.add_argument("--limit", type=int) + + update = commands.add_parser("update", help="change the row with the given id") + update.add_argument("table") + update.add_argument("--id", type=int, required=True, dest="row_id") + update.add_argument("assignments", nargs="+", metavar="column=value") + + delete = commands.add_parser("delete", help="delete the row with the given id") + delete.add_argument("table") + delete.add_argument("--id", type=int, required=True, dest="row_id") + + load = commands.add_parser("import-csv", help="append the rows of a CSV file") + load.add_argument("table") + load.add_argument("file") + + dump = commands.add_parser("export-csv", help="write a table to a CSV file") + dump.add_argument("table") + dump.add_argument("file") + return parser + + +def _id_filter(row_id: int): + return lambda row: row["id"] == row_id + + +def run(args: argparse.Namespace, db: Database, out: TextIO) -> bool: + """Execute one command; returns True when the database must be saved.""" + if args.command == "create": + db.create_table(args.table, [parse_column_spec(spec) for spec in args.columns]) + return True + table: Table = db.table(args.table) + if args.command == "insert": + print(table.insert(**parse_assignments(table.schema, args.assignments)), file=out) + return True + if args.command == "select": + names: Optional[List[str]] = args.columns.split(",") if args.columns else None + rows = table.select(columns=names, order_by=args.order_by, descending=args.desc, limit=args.limit) + write_csv(rows, names or table.schema.names(), out) + return False + if args.command == "update": + changed = table.update(parse_assignments(table.schema, args.assignments), where=_id_filter(args.row_id)) + print("updated %d" % changed, file=out) + return True + if args.command == "delete": + removed = table.delete(where=_id_filter(args.row_id)) + print("deleted %d" % removed, file=out) + return True + if args.command == "import-csv": + print("imported %d" % import_csv(table, args.file), file=out) + return True + print("exported %d" % export_csv(table, args.file), file=out) + return False + + +def main(argv: Optional[Sequence[str]] = None, out: Optional[TextIO] = None) -> int: + out = out if out is not None else sys.stdout + args = build_parser().parse_args(argv) + try: + db = Database(JsonFileStorage(args.db)) + if run(args, db, out): + db.save() + except (MiniDBError, OSError) as exc: + print("error: %s" % exc, file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/csvio.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/csvio.py new file mode 100644 index 00000000..039df875 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/csvio.py @@ -0,0 +1,63 @@ +"""CSV import and export. + +NULL is an empty field; booleans are written as ``true`` and ``false``. +""" + +from __future__ import annotations + +import csv +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, TextIO + +from .errors import SchemaError +from .schema import Schema, parse_text +from .table import Predicate, Table + + +def format_value(value: Any) -> str: + if value is None: + return "" + if isinstance(value, bool): + return "true" if value else "false" + return str(value) + + +def write_csv(rows: Iterable[Mapping[str, Any]], columns: Sequence[str], handle: TextIO) -> None: + """Write a header line and one line per row, using ``\\n`` line endings.""" + writer = csv.writer(handle, lineterminator="\n") + writer.writerow(columns) + for row in rows: + writer.writerow([format_value(row[name]) for name in columns]) + + +def read_csv(handle: TextIO, schema: Schema) -> List[Dict[str, Any]]: + """Read rows written by :func:`write_csv`. An ``id`` column in the file is ignored.""" + reader = csv.DictReader(handle) + header = reader.fieldnames or [] + for name in header: + if not schema.has(name): + raise SchemaError("unknown column in CSV header: %s" % name) + rows = [] + for record in reader: + rows.append({ + name: parse_text(schema.column(name), text) + for name, text in record.items() + if name != "id" and text is not None + }) + return rows + + +def export_csv(table: Table, path: str, where: Optional[Predicate] = None, columns: Optional[Sequence[str]] = None) -> int: + """Write the matching rows to ``path`` and return how many were written.""" + names = list(columns) if columns else table.schema.names() + rows = table.select(where=where, columns=names) + with open(path, "w", encoding="utf-8", newline="") as handle: + write_csv(rows, names, handle) + return len(rows) + + +def import_csv(table: Table, path: str) -> int: + """Insert every row of the CSV file at ``path`` and return how many were added.""" + with open(path, "r", encoding="utf-8", newline="") as handle: + rows = read_csv(handle, table.schema) + table.insert_many(rows) + return len(rows) diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/errors.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/errors.py new file mode 100644 index 00000000..7d43eaef --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/errors.py @@ -0,0 +1,17 @@ +"""Exception hierarchy of minidb.""" + + +class MiniDBError(Exception): + """Base class of every error raised on purpose by minidb.""" + + +class SchemaError(MiniDBError): + """A column definition or a value does not fit the schema.""" + + +class TableError(MiniDBError): + """A table is missing, already exists, or an index request is invalid.""" + + +class RowNotFound(MiniDBError): + """No row with the requested id exists.""" diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/index.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/index.py new file mode 100644 index 00000000..bf372785 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/index.py @@ -0,0 +1,44 @@ +"""Hash indexes for equality lookups.""" + +from __future__ import annotations + +from typing import Any, Dict, Iterable, List, Mapping, Set + + +class HashIndex: + """Maps the values of one column to the ids of the rows holding them. + + NULL values are not indexed: ``lookup(None)`` is always empty. + """ + + def __init__(self, column: str) -> None: + self.column = column + self._ids: Dict[Any, Set[int]] = {} + + def add(self, row: Mapping[str, Any]) -> None: + value = row[self.column] + if value is not None: + self._ids.setdefault(value, set()).add(row["id"]) + + def remove(self, row: Mapping[str, Any]) -> None: + value = row[self.column] + if value is None: + return + bucket = self._ids.get(value) + if bucket is None: + return + bucket.discard(row["id"]) + if not bucket: + del self._ids[value] + + def lookup(self, value: Any) -> List[int]: + """Ids of the rows whose column equals ``value``, in ascending order.""" + return sorted(self._ids.get(value, ())) + + def rebuild(self, rows: Iterable[Mapping[str, Any]]) -> None: + self._ids.clear() + for row in rows: + self.add(row) + + def __len__(self) -> int: + return sum(len(bucket) for bucket in self._ids.values()) diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/schema.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/schema.py new file mode 100644 index 00000000..4fc70790 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/schema.py @@ -0,0 +1,132 @@ +"""Column definitions, type checking and row building.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Dict, Iterable, List, Mapping + +from .errors import SchemaError + +TYPES = ("int", "float", "str", "bool") + +# Words with a fixed meaning in the query language; they cannot name columns. +RESERVED_WORDS = frozenset( + {"AND", "OR", "NOT", "IN", "BETWEEN", "LIKE", "ILIKE", "IS", "NULL", "TRUE", "FALSE"} +) + +_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + +@dataclass(frozen=True) +class Column: + name: str + type: str = "str" + nullable: bool = True + default: Any = None + + def __post_init__(self) -> None: + if not _NAME.fullmatch(self.name): + raise SchemaError("invalid column name: %r" % (self.name,)) + if self.name.upper() in RESERVED_WORDS: + raise SchemaError("column name is a reserved word: %s" % self.name) + if self.type not in TYPES: + raise SchemaError("unknown column type: %r" % (self.type,)) + if self.default is not None: + object.__setattr__(self, "default", coerce_value(self, self.default)) + + def to_dict(self) -> Dict[str, Any]: + return {"name": self.name, "type": self.type, "nullable": self.nullable, "default": self.default} + + +def coerce_value(column: Column, value: Any) -> Any: + """Check ``value`` against the column type and return the value to store.""" + if value is None: + if not column.nullable: + raise SchemaError("column %s may not be NULL" % column.name) + return None + is_number = isinstance(value, (int, float)) and not isinstance(value, bool) + if column.type == "int" and isinstance(value, int) and is_number: + return value + if column.type == "float" and is_number: + return float(value) + if column.type == "str" and isinstance(value, str): + return value + if column.type == "bool" and isinstance(value, bool): + return value + raise SchemaError("column %s expects %s, got %s" % (column.name, column.type, type(value).__name__)) + + +def parse_text(column: Column, text: str) -> Any: + """Convert text from a CSV file or the command line; empty text means NULL.""" + if text == "": + return coerce_value(column, None) + try: + if column.type == "int": + value: Any = int(text) + elif column.type == "float": + value = float(text) + elif column.type == "bool": + lowered = text.lower() + if lowered not in ("true", "false"): + raise ValueError(text) + value = lowered == "true" + else: + value = text + except ValueError: + raise SchemaError("column %s expects %s, got %r" % (column.name, column.type, text)) from None + return coerce_value(column, value) + + +class Schema: + """An ordered set of columns; the first column is always the integer row id.""" + + ID = Column("id", "int", nullable=False) + + def __init__(self, columns: Iterable[Column]) -> None: + self.columns: List[Column] = [self.ID] + seen = {"id"} + for column in columns: + if column.name in seen: + raise SchemaError("duplicate column: %s" % column.name) + seen.add(column.name) + self.columns.append(column) + + def names(self) -> List[str]: + return [c.name for c in self.columns] + + def has(self, name: str) -> bool: + return any(c.name == name for c in self.columns) + + def column(self, name: str) -> Column: + for column in self.columns: + if column.name == name: + return column + raise SchemaError("unknown column: %s" % name) + + def build_row(self, values: Mapping[str, Any], row_id: int) -> Dict[str, Any]: + """A complete row for ``values``: defaults fill the gaps, unknown names are rejected.""" + for name in values: + if name == "id": + raise SchemaError("the id column is assigned automatically") + self.column(name) + row: Dict[str, Any] = {"id": row_id} + for column in self.columns[1:]: + row[column.name] = coerce_value(column, values.get(column.name, column.default)) + return row + + def coerce_changes(self, values: Mapping[str, Any]) -> Dict[str, Any]: + """Validated partial values for an update.""" + changes: Dict[str, Any] = {} + for name, value in values.items(): + if name == "id": + raise SchemaError("the id column cannot be changed") + changes[name] = coerce_value(self.column(name), value) + return changes + + def to_dict(self) -> List[Dict[str, Any]]: + return [c.to_dict() for c in self.columns[1:]] + + @classmethod + def from_dict(cls, spec: List[Dict[str, Any]]) -> "Schema": + return cls(Column(**item) for item in spec) diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/storage.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/storage.py new file mode 100644 index 00000000..6492e467 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/storage.py @@ -0,0 +1,47 @@ +"""Where a database keeps its data between runs.""" + +from __future__ import annotations + +import copy +import json +import os +from typing import Any, Dict, Optional + +from .errors import MiniDBError + + +class MemoryStorage: + """Keeps the data in the process; useful for tests and scratch work.""" + + def __init__(self) -> None: + self._data: Optional[Dict[str, Any]] = None + + def load(self) -> Optional[Dict[str, Any]]: + return copy.deepcopy(self._data) + + def save(self, data: Dict[str, Any]) -> None: + self._data = copy.deepcopy(data) + + +class JsonFileStorage: + """Stores the whole database as one JSON document.""" + + def __init__(self, path: str) -> None: + self.path = path + + def load(self) -> Optional[Dict[str, Any]]: + if not os.path.exists(self.path): + return None + with open(self.path, "r", encoding="utf-8") as handle: + try: + return json.load(handle) + except json.JSONDecodeError as exc: + raise MiniDBError("%s is not a valid database file: %s" % (self.path, exc)) from None + + def save(self, data: Dict[str, Any]) -> None: + """Write the data to a temporary file first so that a crash cannot truncate the database.""" + temporary = self.path + ".tmp" + with open(temporary, "w", encoding="utf-8") as handle: + json.dump(data, handle, indent=2) + handle.write("\n") + os.replace(temporary, self.path) diff --git a/scripts/e2e/codex/tasks/feature-query/seed/minidb/table.py b/scripts/e2e/codex/tasks/feature-query/seed/minidb/table.py new file mode 100644 index 00000000..2f22f23c --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/minidb/table.py @@ -0,0 +1,196 @@ +"""Tables and the database that owns them.""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence + +from .errors import RowNotFound, SchemaError, TableError +from .index import HashIndex +from .schema import Column, Schema +from .storage import MemoryStorage + +Row = Dict[str, Any] +Predicate = Callable[[Row], Any] + + +class Table: + """Rows of one schema, kept in insertion order and addressed by integer id.""" + + def __init__(self, name: str, schema: Schema) -> None: + self.name = name + self.schema = schema + self._rows: Dict[int, Row] = {} + self._next_id = 1 + self._indexes: Dict[str, HashIndex] = {} + + def __len__(self) -> int: + return len(self._rows) + + # -- writing --------------------------------------------------------- + + def insert(self, **values: Any) -> int: + """Add a row and return its id.""" + row = self.schema.build_row(values, self._next_id) + self._rows[row["id"]] = row + self._next_id += 1 + for index in self._indexes.values(): + index.add(row) + return row["id"] + + def insert_many(self, rows: Iterable[Mapping[str, Any]]) -> List[int]: + return [self.insert(**row) for row in rows] + + def update(self, values: Mapping[str, Any], where: Optional[Predicate] = None) -> int: + """Change the matching rows (all rows without ``where``); returns how many changed.""" + changes = self.schema.coerce_changes(values) + matches = self._matcher(where) + targets = [row for row in self._rows.values() if matches(row)] + for row in targets: + for index in self._indexes.values(): + index.remove(row) + row.update(changes) + for index in self._indexes.values(): + index.add(row) + return len(targets) + + def delete(self, where: Optional[Predicate] = None) -> int: + """Remove the matching rows (all rows without ``where``); returns how many were removed.""" + matches = self._matcher(where) + targets = [row for row in self._rows.values() if matches(row)] + for row in targets: + del self._rows[row["id"]] + for index in self._indexes.values(): + index.remove(row) + return len(targets) + + # -- reading --------------------------------------------------------- + + def get(self, row_id: int) -> Row: + try: + return dict(self._rows[row_id]) + except KeyError: + raise RowNotFound("no row with id %r in table %s" % (row_id, self.name)) from None + + def find(self, column: str, value: Any) -> List[Row]: + """Rows whose ``column`` equals ``value``; uses the index when there is one.""" + self.schema.column(column) + index = self._indexes.get(column) + if index is not None: + return [dict(self._rows[i]) for i in index.lookup(value)] + return [dict(r) for r in self._rows.values() if r[column] is not None and r[column] == value] + + def select( + self, + where: Optional[Predicate] = None, + columns: Optional[Sequence[str]] = None, + order_by: Optional[str] = None, + descending: bool = False, + limit: Optional[int] = None, + ) -> List[Row]: + """Rows for which ``where(row)`` is true, optionally sorted, limited and projected. + + Rows whose ``order_by`` value is NULL always come last. + """ + matches = self._matcher(where) + rows = [row for row in self._rows.values() if matches(row)] + if order_by is not None: + rows = self._ordered(rows, order_by, descending) + if limit is not None: + rows = rows[:limit] + return [self._project(row, columns) for row in rows] + + def count(self, where: Optional[Predicate] = None) -> int: + matches = self._matcher(where) + return sum(1 for row in self._rows.values() if matches(row)) + + # -- indexes --------------------------------------------------------- + + def create_index(self, column: str) -> None: + self.schema.column(column) + if column in self._indexes: + raise TableError("column %s is already indexed" % column) + index = HashIndex(column) + index.rebuild(self._rows.values()) + self._indexes[column] = index + + def indexed_columns(self) -> List[str]: + return sorted(self._indexes) + + # -- internals ------------------------------------------------------- + + @staticmethod + def _matcher(where: Optional[Predicate]) -> Predicate: + if where is None: + return lambda row: True + if callable(where): + return where + raise TypeError("where must be a callable or None, not %s" % type(where).__name__) + + def _ordered(self, rows: List[Row], order_by: str, descending: bool) -> List[Row]: + self.schema.column(order_by) + present = [row for row in rows if row[order_by] is not None] + missing = [row for row in rows if row[order_by] is None] + present.sort(key=lambda row: row[order_by], reverse=descending) + return present + missing + + def _project(self, row: Row, columns: Optional[Sequence[str]]) -> Row: + if columns is None: + return dict(row) + for name in columns: + self.schema.column(name) + return {name: row[name] for name in columns} + + # -- persistence ----------------------------------------------------- + + def to_dict(self) -> Dict[str, Any]: + return { + "schema": self.schema.to_dict(), + "next_id": self._next_id, + "indexes": self.indexed_columns(), + "rows": [dict(row) for row in self._rows.values()], + } + + @classmethod + def from_dict(cls, name: str, spec: Mapping[str, Any]) -> "Table": + table = cls(name, Schema.from_dict(spec["schema"])) + for row in spec["rows"]: + table._rows[row["id"]] = dict(row) + table._next_id = spec["next_id"] + for column in spec.get("indexes", []): + table.create_index(column) + return table + + +class Database: + """A named collection of tables backed by a storage object.""" + + def __init__(self, storage: Optional[Any] = None) -> None: + self.storage = storage if storage is not None else MemoryStorage() + self._tables: Dict[str, Table] = {} + data = self.storage.load() + if data: + for name, spec in data["tables"].items(): + self._tables[name] = Table.from_dict(name, spec) + + def create_table(self, name: str, columns: Iterable[Column]) -> Table: + if name in self._tables: + raise TableError("table already exists: %s" % name) + table = Table(name, Schema(columns)) + self._tables[name] = table + return table + + def table(self, name: str) -> Table: + try: + return self._tables[name] + except KeyError: + raise TableError("no such table: %s" % name) from None + + def drop_table(self, name: str) -> None: + self.table(name) + del self._tables[name] + + def table_names(self) -> List[str]: + return sorted(self._tables) + + def save(self) -> None: + self.storage.save({"version": 1, "tables": {n: t.to_dict() for n, t in self._tables.items()}}) diff --git a/scripts/e2e/codex/tasks/feature-query/seed/tests/test_csv_cli.py b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_csv_cli.py new file mode 100644 index 00000000..6dd597f7 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_csv_cli.py @@ -0,0 +1,133 @@ +import contextlib +import io +import os +import tempfile +import unittest + +from minidb import Column, Database +from minidb.cli import main, parse_assignments, parse_column_spec +from minidb.csvio import export_csv, import_csv, read_csv, write_csv +from minidb.errors import SchemaError + + +def people_table(): + db = Database() + people = db.create_table("people", [Column("name"), Column("age", "int"), Column("active", "bool")]) + people.insert_many([ + {"name": "Ann", "age": 31, "active": True}, + {"name": "Bob, Jr.", "age": None, "active": False}, + ]) + return people + + +class CsvTests(unittest.TestCase): + def test_write_csv_format(self): + people = people_table() + buffer = io.StringIO() + write_csv(people.select(), people.schema.names(), buffer) + self.assertEqual(buffer.getvalue(), 'id,name,age,active\n1,Ann,31,true\n2,"Bob, Jr.",,false\n') + + def test_round_trip_through_a_file(self): + people = people_table() + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "people.csv") + self.assertEqual(export_csv(people, path), 2) + other = Database().create_table("people", [Column("name"), Column("age", "int"), Column("active", "bool")]) + self.assertEqual(import_csv(other, path), 2) + self.assertEqual(other.select(), people.select()) + + def test_import_ignores_id_column_and_checks_header(self): + schema = people_table().schema + rows = read_csv(io.StringIO("id,name\n7,Zed\n"), schema) + self.assertEqual(rows, [{"name": "Zed"}]) + with self.assertRaises(SchemaError): + read_csv(io.StringIO("nombre\nZed\n"), schema) + + def test_export_with_callable_filter(self): + people = people_table() + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "out.csv") + written = export_csv(people, path, where=lambda row: row["active"], columns=["name"]) + with open(path, encoding="utf-8") as handle: + self.assertEqual(handle.read(), "name\nAnn\n") + self.assertEqual(written, 1) + + +class ParsingTests(unittest.TestCase): + def test_column_specs(self): + self.assertEqual(parse_column_spec("age:int"), Column("age", "int")) + self.assertEqual(parse_column_spec("name:str:required"), Column("name", "str", nullable=False)) + with self.assertRaises(SchemaError): + parse_column_spec("age") + with self.assertRaises(SchemaError): + parse_column_spec("age:int:maybe") + + def test_assignments(self): + schema = people_table().schema + self.assertEqual(parse_assignments(schema, ["name=Ann", "age=", "active=true"]), + {"name": "Ann", "age": None, "active": True}) + with self.assertRaises(SchemaError): + parse_assignments(schema, ["age"]) + + +class CliTests(unittest.TestCase): + def setUp(self): + self._folder = tempfile.TemporaryDirectory() + self.addCleanup(self._folder.cleanup) + self.db = os.path.join(self._folder.name, "test.json") + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(err): + code = main(["--db", self.db, *args], out=out) + return code, out.getvalue(), err.getvalue() + + def setup_table(self): + self.assertEqual(self.run_cli("create", "people", "name:str:required", "age:int", "city:str")[0], 0) + for assignments in (["name=Ann", "age=31", "city=Berlin"], ["name=Bob", "age=25"], ["name=Cid", "city=Rome"]): + self.assertEqual(self.run_cli("insert", "people", *assignments)[0], 0) + + def test_insert_prints_ids_and_select_prints_csv(self): + self.setup_table() + code, out, _ = self.run_cli("select", "people") + self.assertEqual(code, 0) + self.assertEqual(out, "id,name,age,city\n1,Ann,31,Berlin\n2,Bob,25,\n3,Cid,,Rome\n") + + def test_select_options(self): + self.setup_table() + _, out, _ = self.run_cli("select", "people", "--columns", "name,age", "--order-by", "age", "--desc", "--limit", "2") + self.assertEqual(out, "name,age\nAnn,31\nBob,25\n") + + def test_update_and_delete_by_id(self): + self.setup_table() + self.assertEqual(self.run_cli("update", "people", "--id", "2", "city=Paris", "age=")[1], "updated 1\n") + self.assertEqual(self.run_cli("delete", "people", "--id", "1")[1], "deleted 1\n") + self.assertEqual(self.run_cli("delete", "people", "--id", "77")[1], "deleted 0\n") + _, out, _ = self.run_cli("select", "people") + self.assertEqual(out, "id,name,age,city\n2,Bob,,Paris\n3,Cid,,Rome\n") + + def test_data_persists_between_runs(self): + self.setup_table() + self.assertTrue(os.path.exists(self.db)) + _, out, _ = self.run_cli("select", "people", "--columns", "id") + self.assertEqual(out.splitlines(), ["id", "1", "2", "3"]) + + def test_errors_exit_with_status_two(self): + self.setup_table() + for args in (["select", "nobody"], ["insert", "people", "age=3"], ["insert", "people", "name=X", "age=old"], + ["select", "people", "--order-by", "height"]): + code, out, err = self.run_cli(*args) + self.assertEqual((code, out), (2, ""), args) + self.assertTrue(err.startswith("error: "), args) + + def test_import_and_export(self): + self.setup_table() + path = os.path.join(self._folder.name, "people.csv") + self.assertEqual(self.run_cli("export-csv", "people", path), (0, "exported 3\n", "")) + self.assertEqual(self.run_cli("import-csv", "people", path), (0, "imported 3\n", "")) + _, out, _ = self.run_cli("select", "people", "--columns", "name") + self.assertEqual(out.splitlines(), ["name", "Ann", "Bob", "Cid", "Ann", "Bob", "Cid"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/seed/tests/test_index_storage.py b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_index_storage.py new file mode 100644 index 00000000..45543eb2 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_index_storage.py @@ -0,0 +1,72 @@ +import json +import os +import tempfile +import unittest + +from minidb.errors import MiniDBError +from minidb.index import HashIndex +from minidb.storage import JsonFileStorage, MemoryStorage + + +class HashIndexTests(unittest.TestCase): + def test_add_lookup_remove(self): + index = HashIndex("city") + index.add({"id": 2, "city": "Rome"}) + index.add({"id": 1, "city": "Rome"}) + index.add({"id": 3, "city": "Paris"}) + self.assertEqual(index.lookup("Rome"), [1, 2]) + index.remove({"id": 1, "city": "Rome"}) + self.assertEqual(index.lookup("Rome"), [2]) + self.assertEqual(index.lookup("Oslo"), []) + self.assertEqual(len(index), 2) + + def test_nulls_are_not_indexed(self): + index = HashIndex("city") + index.add({"id": 1, "city": None}) + self.assertEqual(index.lookup(None), []) + self.assertEqual(len(index), 0) + + def test_rebuild(self): + index = HashIndex("n") + index.add({"id": 9, "n": 1}) + index.rebuild([{"id": 1, "n": 5}, {"id": 2, "n": 5}]) + self.assertEqual(index.lookup(1), []) + self.assertEqual(index.lookup(5), [1, 2]) + + +class StorageTests(unittest.TestCase): + def test_memory_storage_keeps_copies(self): + storage = MemoryStorage() + self.assertIsNone(storage.load()) + data = {"tables": {"t": {"rows": [1]}}} + storage.save(data) + data["tables"]["t"]["rows"].append(2) + self.assertEqual(storage.load(), {"tables": {"t": {"rows": [1]}}}) + + def test_json_file_round_trip(self): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "db.json") + storage = JsonFileStorage(path) + self.assertIsNone(storage.load()) + storage.save({"tables": {}, "version": 1}) + self.assertEqual(storage.load(), {"tables": {}, "version": 1}) + self.assertFalse(os.path.exists(path + ".tmp")) + + def test_corrupt_file_is_reported(self): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "db.json") + with open(path, "w", encoding="utf-8") as handle: + handle.write("{not json") + with self.assertRaises(MiniDBError): + JsonFileStorage(path).load() + + def test_file_is_plain_json(self): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "db.json") + JsonFileStorage(path).save({"a": [1, 2]}) + with open(path, encoding="utf-8") as handle: + self.assertEqual(json.load(handle), {"a": [1, 2]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/seed/tests/test_schema.py b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_schema.py new file mode 100644 index 00000000..68f69a27 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_schema.py @@ -0,0 +1,94 @@ +import unittest + +from minidb.errors import SchemaError +from minidb.schema import Column, Schema, coerce_value, parse_text + + +class ColumnTests(unittest.TestCase): + def test_rejects_bad_names(self): + for name in ("", "1abc", "a-b", "a b", "id!"): + with self.assertRaises(SchemaError, msg=name): + Column(name) + + def test_rejects_reserved_words_in_any_case(self): + for name in ("and", "Not", "NULL", "between", "true"): + with self.assertRaises(SchemaError, msg=name): + Column(name) + + def test_names_starting_with_a_keyword_are_fine(self): + for name in ("note", "android", "island", "origin", "nullable", "in_stock"): + self.assertEqual(Column(name).name, name) + + def test_unknown_type(self): + with self.assertRaises(SchemaError): + Column("x", "decimal") + + def test_default_is_checked(self): + with self.assertRaises(SchemaError): + Column("x", "int", default="seven") + self.assertEqual(Column("x", "float", default=2).default, 2.0) + + +class CoerceTests(unittest.TestCase): + def test_int_rejects_bool_and_float(self): + column = Column("n", "int") + self.assertEqual(coerce_value(column, 5), 5) + with self.assertRaises(SchemaError): + coerce_value(column, True) + with self.assertRaises(SchemaError): + coerce_value(column, 5.5) + + def test_float_accepts_int(self): + value = coerce_value(Column("f", "float"), 3) + self.assertEqual(value, 3.0) + self.assertIsInstance(value, float) + + def test_null_needs_nullable_column(self): + self.assertIsNone(coerce_value(Column("s"), None)) + with self.assertRaises(SchemaError): + coerce_value(Column("s", nullable=False), None) + + def test_parse_text(self): + self.assertEqual(parse_text(Column("n", "int"), "42"), 42) + self.assertEqual(parse_text(Column("f", "float"), "2.5"), 2.5) + self.assertIs(parse_text(Column("b", "bool"), "TRUE"), True) + self.assertEqual(parse_text(Column("s"), "hello world"), "hello world") + self.assertIsNone(parse_text(Column("n", "int"), "")) + with self.assertRaises(SchemaError): + parse_text(Column("n", "int"), "4x") + with self.assertRaises(SchemaError): + parse_text(Column("b", "bool"), "yes") + + +class SchemaTests(unittest.TestCase): + def test_id_column_comes_first(self): + schema = Schema([Column("name"), Column("age", "int")]) + self.assertEqual(schema.names(), ["id", "name", "age"]) + self.assertTrue(schema.has("age")) + self.assertFalse(schema.has("height")) + + def test_duplicate_and_id_columns_are_rejected(self): + with self.assertRaises(SchemaError): + Schema([Column("a"), Column("a")]) + with self.assertRaises(SchemaError): + Schema([Column("id", "int")]) + + def test_build_row_applies_defaults(self): + schema = Schema([Column("name", nullable=False, default="n/a"), Column("age", "int")]) + self.assertEqual(schema.build_row({"age": 4}, 7), {"id": 7, "name": "n/a", "age": 4}) + + def test_build_row_rejects_unknown_columns_and_id(self): + schema = Schema([Column("name")]) + with self.assertRaises(SchemaError): + schema.build_row({"nam": "x"}, 1) + with self.assertRaises(SchemaError): + schema.build_row({"id": 5}, 1) + + def test_round_trip(self): + schema = Schema([Column("name", nullable=False), Column("score", "float", default=1.5)]) + again = Schema.from_dict(schema.to_dict()) + self.assertEqual(again.columns, schema.columns) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/seed/tests/test_table.py b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_table.py new file mode 100644 index 00000000..499db8c4 --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/seed/tests/test_table.py @@ -0,0 +1,175 @@ +import unittest + +from minidb import Column, Database, JsonFileStorage, MemoryStorage +from minidb.errors import RowNotFound, SchemaError, TableError + + +def make_people(): + db = Database() + people = db.create_table("people", [ + Column("name", "str", nullable=False), + Column("age", "int"), + Column("city", "str"), + ]) + people.insert_many([ + {"name": "Ann", "age": 31, "city": "Berlin"}, + {"name": "Bob", "age": 25, "city": "Paris"}, + {"name": "Cid", "age": None, "city": "Berlin"}, + {"name": "Dee", "age": 40, "city": None}, + ]) + return people + + +class InsertTests(unittest.TestCase): + def test_ids_are_sequential_and_never_reused(self): + people = make_people() + self.assertEqual(people.insert(name="Eve"), 5) + people.delete(where=lambda row: row["id"] == 5) + self.assertEqual(people.insert(name="Fay"), 6) + + def test_missing_values_become_null(self): + people = make_people() + row = people.get(people.insert(name="Eve")) + self.assertEqual(row, {"id": 5, "name": "Eve", "age": None, "city": None}) + + def test_invalid_rows_are_rejected(self): + people = make_people() + with self.assertRaises(SchemaError): + people.insert(age=3) + with self.assertRaises(SchemaError): + people.insert(name="X", age="old") + self.assertEqual(len(people), 4) + + +class SelectTests(unittest.TestCase): + def setUp(self): + self.people = make_people() + + def names(self, rows): + return [row["name"] for row in rows] + + def test_select_all(self): + self.assertEqual(self.names(self.people.select()), ["Ann", "Bob", "Cid", "Dee"]) + + def test_select_with_callable(self): + rows = self.people.select(where=lambda row: row["city"] == "Berlin") + self.assertEqual(self.names(rows), ["Ann", "Cid"]) + + def test_returned_rows_are_copies(self): + row = self.people.select()[0] + row["name"] = "changed" + self.assertEqual(self.people.get(1)["name"], "Ann") + + def test_order_by_puts_nulls_last_in_both_directions(self): + self.assertEqual(self.names(self.people.select(order_by="age")), ["Bob", "Ann", "Dee", "Cid"]) + self.assertEqual(self.names(self.people.select(order_by="age", descending=True)), ["Dee", "Ann", "Bob", "Cid"]) + + def test_limit_and_columns(self): + rows = self.people.select(columns=["name", "id"], order_by="name", descending=True, limit=2) + self.assertEqual(rows, [{"name": "Dee", "id": 4}, {"name": "Cid", "id": 3}]) + + def test_unknown_columns_are_rejected(self): + with self.assertRaises(SchemaError): + self.people.select(order_by="height") + with self.assertRaises(SchemaError): + self.people.select(columns=["height"]) + + def test_where_must_be_callable_or_none(self): + with self.assertRaises(TypeError): + self.people.select(where=42) + + def test_count(self): + self.assertEqual(self.people.count(), 4) + self.assertEqual(self.people.count(where=lambda row: row["age"] is None), 1) + + def test_get_unknown_id(self): + with self.assertRaises(RowNotFound): + self.people.get(99) + + +class UpdateDeleteTests(unittest.TestCase): + def setUp(self): + self.people = make_people() + + def test_update_matching_rows(self): + changed = self.people.update({"city": "Rome"}, where=lambda row: row["city"] == "Berlin") + self.assertEqual(changed, 2) + self.assertEqual([r["city"] for r in self.people.select()], ["Rome", "Paris", "Rome", None]) + + def test_update_without_where_changes_everything(self): + self.assertEqual(self.people.update({"age": 1}), 4) + + def test_update_validates_before_changing(self): + with self.assertRaises(SchemaError): + self.people.update({"age": "x"}) + with self.assertRaises(SchemaError): + self.people.update({"id": 9}) + self.assertEqual(self.people.get(1)["age"], 31) + + def test_failed_predicate_changes_nothing(self): + def boom(row): + if row["id"] == 3: + raise ValueError("boom") + return True + + with self.assertRaises(ValueError): + self.people.update({"age": 0}, where=boom) + self.assertEqual(self.people.get(1)["age"], 31) + + def test_delete(self): + removed = self.people.delete(where=lambda row: row["age"] is None) + self.assertEqual(removed, 1) + self.assertEqual(len(self.people), 3) + self.assertEqual(self.people.delete(), 3) + + +class IndexTests(unittest.TestCase): + def test_index_follows_writes(self): + people = make_people() + people.create_index("city") + self.assertEqual([r["name"] for r in people.find("city", "Berlin")], ["Ann", "Cid"]) + people.update({"city": "Berlin"}, where=lambda row: row["name"] == "Bob") + people.insert(name="Eve", city="Berlin") + people.delete(where=lambda row: row["name"] == "Ann") + self.assertEqual([r["name"] for r in people.find("city", "Berlin")], ["Bob", "Cid", "Eve"]) + self.assertEqual(people.find("city", None), []) + + def test_find_without_index_matches_indexed_find(self): + plain, indexed = make_people(), make_people() + indexed.create_index("age") + self.assertEqual(plain.find("age", 25), indexed.find("age", 25)) + + def test_duplicate_index(self): + people = make_people() + people.create_index("city") + with self.assertRaises(TableError): + people.create_index("city") + + +class DatabaseTests(unittest.TestCase): + def test_tables(self): + db = Database() + db.create_table("a", [Column("x")]) + with self.assertRaises(TableError): + db.create_table("a", [Column("x")]) + with self.assertRaises(TableError): + db.table("b") + db.drop_table("a") + self.assertEqual(db.table_names(), []) + + def test_save_and_reload_keeps_rows_ids_and_indexes(self): + storage = MemoryStorage() + db = Database(storage) + people = db.create_table("people", [Column("name"), Column("age", "int")]) + people.insert_many([{"name": "Ann", "age": 3}, {"name": "Bob", "age": 4}]) + people.delete(where=lambda row: row["id"] == 2) + people.create_index("name") + db.save() + again = Database(storage).table("people") + self.assertEqual(again.select(), [{"id": 1, "name": "Ann", "age": 3}]) + self.assertEqual(again.indexed_columns(), ["name"]) + self.assertEqual(again.insert(name="Cy"), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/feature-query/task.md b/scripts/e2e/codex/tasks/feature-query/task.md new file mode 100644 index 00000000..226f2c2f --- /dev/null +++ b/scripts/e2e/codex/tasks/feature-query/task.md @@ -0,0 +1,38 @@ +--- +id: feature-query +title: Implement the where query language of minidb from its specification +kind: feature +expected_rounds: 20-45 +--- +# Implement the where query language of minidb from its specification + +Seed: package `minidb/` (9 modules, about 640 lines), `SPEC.md` (180 lines, the precise language definition), `README.md`, and 55 visible unittest tests +(all pass on the seed). The agent must create `minidb/query.py` (recursive-descent parser with three-valued logic), wire it into `Table.select/update/delete/count` +through the single `Table._matcher` choke point, add `--where` to the CLI (`select`; `update` and `delete` with `--id`/`--where` mutually exclusive), write +`tests/test_query.py` with at least 25 test methods, and document the feature in `README.md`. + +Reference solution (`reference/overlay/`): `minidb/query.py` (387 lines), small edits to `table.py` and `cli.py`, README section, `tests/test_query.py` (31 tests). + +Acceptance (`accept.py`): + +* the pristine `tests/` files and `SPEC.md` are byte-identical; +* the pristine visible tests pass (run from a clean copy of `tests/`); +* `hidden/test_hidden_spec.py` passes: 32 test methods, about 250 table-driven cases (select results, syntax error positions, name errors, type errors, + short-circuit rules, `Table`/CLI integration). Every case is determined by `SPEC.md` alone; +* `tests/test_query.py` exists, has at least 25 test methods that contain an assertion call, mentions `minidb` and `where`, and passes (at least 25 tests run); +* `README.md` mentions `--where`. + +## Prompt + +This repository is `minidb`, a small table store with a command line tool (see `README.md`). `Table.select`, `Table.update`, `Table.delete` and `Table.count` currently take a Python callable as `where`. `SPEC.md` defines a textual `where` query language for them, but nothing implements it yet. Please implement it: + +1. Create `minidb/query.py` that implements `SPEC.md` exactly, including `compile_where(text, columns)` and the exception classes that the spec names. +2. Make `Table.select`, `Table.update`, `Table.delete` and `Table.count` accept a query string as `where`. Callables and `None` must keep working as before. +3. Add `--where EXPRESSION` to the `select`, `update` and `delete` commands of the command line tool, as described in the spec. +4. Add at least 25 unit tests for the language in `tests/test_query.py` (unittest). Cover parsing and precedence, every operator, NULL handling, and the error classes including the error positions. +5. Document the feature in `README.md` (a syntax summary, a Python example and a command line example). + +Where the spec is precise (error positions, evaluation order, NULL logic, type errors) follow it exactly. Do not change `SPEC.md` or the existing tests, and keep them passing: `python3 -m unittest discover -s tests`. Use only the standard library and stay compatible with Python 3.9 or newer. + +When you are done, reply with a short summary of what you implemented and which files you changed. + diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/accept.py b/scripts/e2e/codex/tasks/fixbug-ledger/accept.py new file mode 100644 index 00000000..5a222bf2 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/accept.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Acceptance check for task fixbug-ledger. + +Usage: python3 accept.py WORKSPACE +Exit 0 when the task is done; any other exit code means not done. The workspace is never modified: everything runs in a temporary copy. +""" + +import hashlib +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PRISTINE = HERE / "hidden" / "pristine_tests" +HIDDEN_TESTS = HERE / "hidden" / "test_hidden.py" +IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".git") + +failed = [] + + +def check(name, ok, detail=""): + if ok: + print("PASS " + name) + else: + print("FAIL %s :: %s" % (name, detail.strip()[-1500:])) + failed.append(name) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def run_unittest(cwd, start_dir, timeout=100): + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0") + try: + proc = subprocess.run( + [sys.executable, "-m", "unittest", "discover", "-s", start_dir], + cwd=str(cwd), env=env, capture_output=True, text=True, timeout=timeout, + ) + except subprocess.TimeoutExpired: + return False, "timeout" + return proc.returncode == 0, proc.stdout + proc.stderr + + +def main(): + if len(sys.argv) != 2: + print("usage: accept.py WORKSPACE") + return 2 + workspace = Path(sys.argv[1]).resolve() + if not workspace.is_dir(): + print("FAIL workspace :: not a directory") + return 2 + + # 0. nothing may shadow the standard library or hook the interpreter start-up + shadow = {"sitecustomize", "usercustomize", "unittest", "decimal", "datetime", "csv", "json", "argparse", "calendar"} + clashes = sorted(p.name for p in workspace.iterdir() if p.stem in shadow) + check("no-shadowing", not clashes, "top-level files shadow standard modules: %s" % ", ".join(clashes)) + + # 1. the pristine tests must be untouched + for src in sorted(PRISTINE.rglob("*")): + if not src.is_file() or "__pycache__" in src.parts: + continue + rel = src.relative_to(PRISTINE) + target = workspace / "tests" / rel + same = target.is_file() and digest(target) == digest(src) + check("tests-untouched:" + rel.as_posix(), same, "tests/%s is missing or was modified" % rel.as_posix()) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) / "ws" + shutil.copytree(workspace, work, ignore=IGNORE) + # run the pristine tests, not whatever is in tests/ now + shutil.rmtree(work / "tests", ignore_errors=True) + shutil.copytree(PRISTINE, work / "tests", ignore=IGNORE) + ok, out = run_unittest(work, "tests") + check("visible-tests", ok, out) + + hidden_dir = work / "_hidden" + hidden_dir.mkdir() + shutil.copy(HIDDEN_TESTS, hidden_dir / "test_hidden.py") + ok, out = run_unittest(work, "_hidden") + check("hidden-tests", ok, out) + + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/helpers.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/helpers.py new file mode 100644 index 00000000..5bad8eb9 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/helpers.py @@ -0,0 +1,36 @@ +"""Shared fixtures for the ledger tests.""" + +from datetime import date + +from ledger import Journal, Money, Transaction, default_chart + + +def eur(text): + return Money(text, "EUR") + + +def sample_journal(): + """Three months of activity in 2024; the bank balance ends at 5253.35.""" + journal = Journal(default_chart()) + journal.post_all([ + Transaction.transfer("t1", date(2024, 1, 5), "Opening deposit", "1000", "3000", eur("5000.00")), + Transaction.transfer("t2", date(2024, 1, 10), "Consulting invoice", "1000", "4000", eur("1200.00")), + Transaction.transfer("t3", date(2024, 1, 15), "January rent", "5000", "1000", eur("800.00")), + Transaction.transfer("t4", date(2024, 2, 3), "Groceries", "5100", "1000", eur("150.25")), + Transaction.transfer("t5", date(2024, 2, 20), "Consulting invoice", "1000", "4000", eur("900.00")), + Transaction.transfer("t6", date(2024, 2, 28), "Electricity", "5200", "1000", eur("96.40")), + Transaction.transfer("t7", date(2024, 3, 1), "March rent", "5000", "1000", eur("800.00")), + ]) + return journal + + +def two_year_journal(): + """Activity in January 2023 and January 2024 plus December 2023.""" + journal = Journal(default_chart()) + journal.post_all([ + Transaction.transfer("a1", date(2023, 1, 9), "Salary", "1000", "4000", eur("2000.00")), + Transaction.transfer("a2", date(2023, 12, 20), "Salary", "1000", "4000", eur("2100.00")), + Transaction.transfer("a3", date(2024, 1, 8), "Salary", "1000", "4000", eur("2200.00")), + Transaction.transfer("a4", date(2024, 1, 20), "Rent", "5000", "1000", eur("700.00")), + ]) + return journal diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_accounts.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_accounts.py new file mode 100644 index 00000000..178c0610 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_accounts.py @@ -0,0 +1,69 @@ +import unittest + +from ledger.accounts import Account, AccountKind, Chart, DuplicateAccount, UnknownAccount, default_chart + + +class AccountKindTests(unittest.TestCase): + def test_normal_sides(self): + self.assertEqual(AccountKind.ASSET.normal_side, "debit") + self.assertEqual(AccountKind.EXPENSE.normal_side, "debit") + self.assertEqual(AccountKind.LIABILITY.normal_side, "credit") + self.assertEqual(AccountKind.EQUITY.normal_side, "credit") + self.assertEqual(AccountKind.INCOME.normal_side, "credit") + + +class AccountTests(unittest.TestCase): + def test_labels_from_iterable(self): + account = Account("1000", "Bank", AccountKind.ASSET, ["cash", "main"]) + self.assertEqual(account.labels, ["cash", "main"]) + self.assertTrue(account.has_label("main")) + + def test_add_label_ignores_duplicates(self): + account = Account("1000", "Bank", AccountKind.ASSET) + account.add_label("cash") + account.add_label("cash") + self.assertEqual(account.labels, ["cash"]) + self.assertTrue(account.has_label("cash")) + + def test_labels_belong_to_one_account(self): + first = Account("1000", "Bank", AccountKind.ASSET) + second = Account("1100", "Receivables", AccountKind.ASSET) + first.add_label("liquid") + self.assertEqual(second.labels, []) + self.assertFalse(second.has_label("liquid")) + + +class ChartTests(unittest.TestCase): + def setUp(self): + self.chart = Chart([ + Account("2000", "Payables", AccountKind.LIABILITY), + Account("1000", "Bank", AccountKind.ASSET), + Account("1100", "Receivables", AccountKind.ASSET), + ]) + + def test_iteration_is_sorted_by_code(self): + self.assertEqual([a.code for a in self.chart], ["1000", "1100", "2000"]) + + def test_get_unknown_and_duplicate(self): + self.assertEqual(self.chart.get("1000").name, "Bank") + with self.assertRaises(UnknownAccount): + self.chart.get("9999") + with self.assertRaises(DuplicateAccount): + self.chart.add(Account("1000", "Other", AccountKind.ASSET)) + + def test_by_kind(self): + self.assertEqual([a.code for a in self.chart.by_kind(AccountKind.ASSET)], ["1000", "1100"]) + + def test_by_label_only_returns_labelled_accounts(self): + self.chart.get("1100").add_label("trade") + self.assertEqual([a.code for a in self.chart.by_label("trade")], ["1100"]) + + def test_default_chart(self): + chart = default_chart() + self.assertIn("1000", chart) + self.assertEqual(len(chart), 11) + self.assertEqual(chart.get("5000").kind, AccountKind.EXPENSE) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_calendar.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_calendar.py new file mode 100644 index 00000000..e9ce9a1c --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_calendar.py @@ -0,0 +1,67 @@ +import unittest +from datetime import date + +from ledger.calendar import BusinessCalendar, fixed_holidays + +# 2024-03-01 is a Friday, 2024-05-01 (Labour Day) a Wednesday, 2024-12-25 a Wednesday. + + +class CalendarTests(unittest.TestCase): + def setUp(self): + self.cal = BusinessCalendar.for_years([2024]) + + def test_fixed_holidays(self): + self.assertEqual( + sorted(fixed_holidays(2024)), + [date(2024, 1, 1), date(2024, 5, 1), date(2024, 12, 25), date(2024, 12, 26)], + ) + + def test_is_business_day(self): + self.assertTrue(self.cal.is_business_day(date(2024, 3, 1))) + self.assertFalse(self.cal.is_business_day(date(2024, 3, 2))) + self.assertFalse(self.cal.is_business_day(date(2024, 3, 3))) + self.assertFalse(self.cal.is_business_day(date(2024, 5, 1))) + + def test_custom_weekend(self): + cal = BusinessCalendar(weekend=(4, 5)) + self.assertFalse(cal.is_business_day(date(2024, 3, 1))) + self.assertTrue(cal.is_business_day(date(2024, 3, 3))) + + def test_next_and_previous_business_day(self): + self.assertEqual(self.cal.next_business_day(date(2024, 3, 1)), date(2024, 3, 1)) + self.assertEqual(self.cal.next_business_day(date(2024, 3, 2)), date(2024, 3, 4)) + self.assertEqual(self.cal.next_business_day(date(2024, 12, 25)), date(2024, 12, 27)) + self.assertEqual(self.cal.previous_business_day(date(2024, 3, 3)), date(2024, 3, 1)) + + def test_add_business_days_from_a_business_day(self): + self.assertEqual(self.cal.add_business_days(date(2024, 3, 1), 1), date(2024, 3, 4)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 4), 5), date(2024, 3, 11)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 4), -1), date(2024, 3, 1)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 4), 0), date(2024, 3, 4)) + + def test_add_business_days_skips_holidays(self): + self.assertEqual(self.cal.add_business_days(date(2024, 4, 30), 1), date(2024, 5, 2)) + self.assertEqual(self.cal.add_business_days(date(2024, 12, 24), 2), date(2024, 12, 30)) + + def test_add_business_days_from_a_saturday(self): + self.assertEqual(self.cal.add_business_days(date(2024, 3, 2), 1), date(2024, 3, 4)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 2), 3), date(2024, 3, 6)) + + def test_add_business_days_from_a_holiday(self): + self.assertEqual(self.cal.add_business_days(date(2024, 5, 1), 1), date(2024, 5, 2)) + + def test_business_days_between(self): + self.assertEqual(self.cal.business_days_between(date(2024, 3, 1), date(2024, 3, 4)), 1) + self.assertEqual(self.cal.business_days_between(date(2024, 3, 4), date(2024, 3, 8)), 4) + self.assertEqual(self.cal.business_days_between(date(2024, 3, 4), date(2024, 3, 4)), 0) + self.assertEqual(self.cal.business_days_between(date(2024, 3, 8), date(2024, 3, 4)), -4) + self.assertEqual(self.cal.business_days_between(date(2024, 4, 30), date(2024, 5, 3)), 2) + + def test_business_days_in_month(self): + self.assertEqual(self.cal.business_days_in_month(2024, 3), 21) + self.assertEqual(self.cal.business_days_in_month(2024, 5), 22) + self.assertEqual(self.cal.business_days_in_month(2024, 12), 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_cli.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_cli.py new file mode 100644 index 00000000..1e3d820e --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_cli.py @@ -0,0 +1,66 @@ +import contextlib +import io +import os +import tempfile +import unittest + +from ledger import cli + +SINGLE_YEAR = """date,description,amount,category +2024-01-05,Opening deposit,5000.00,3000 +2024-01-10,Consulting invoice,1200.00,4000 +2024-02-03,Groceries,-150.25,5100 +2024-02-20,Consulting invoice,900.00,4000 +""" + +TWO_YEARS = """date,description,amount,category +2023-01-09,Salary,2000.00,4000 +2023-12-20,Salary,2100.00,4000 +2024-01-08,Salary,2200.00,4000 +2024-01-20,Rent,-700.00,5000 +""" + + +class CliTests(unittest.TestCase): + def run_cli(self, content, *args): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "statement.csv") + with open(path, "w", encoding="utf-8") as handle: + handle.write(content) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(err): + code = cli.main([args[0], path, *args[1:]], out=out) + return code, out.getvalue(), err.getvalue() + + def test_balance(self): + code, out, _ = self.run_cli(SINGLE_YEAR, "balance") + self.assertEqual((code, out), (0, "6949.75\n")) + + def test_balance_styles(self): + _, out, _ = self.run_cli(SINGLE_YEAR, "balance", "--style", "german") + self.assertEqual(out, "6.949,75\n") + + def test_monthly_within_one_year(self): + code, out, _ = self.run_cli(SINGLE_YEAR, "monthly") + self.assertEqual((code, out), (0, "2024-01 6200.00\n2024-02 749.75\n")) + + def test_monthly_across_years(self): + _, out, _ = self.run_cli(TWO_YEARS, "monthly") + self.assertEqual(out.splitlines(), ["2023-01 2000.00", "2023-12 2100.00", "2024-01 1500.00"]) + + def test_trial_and_export(self): + _, trial, _ = self.run_cli(SINGLE_YEAR, "trial") + self.assertIn("1000,Bank,6949.75,0.00", trial.splitlines()) + _, export, _ = self.run_cli(SINGLE_YEAR, "export") + self.assertEqual(len(export.splitlines()), 1 + 2 * 4) + + def test_errors_return_two(self): + code, _, err = self.run_cli("date,amount\n", "balance") + self.assertEqual(code, 2) + self.assertIn("missing columns", err) + code, _, err = self.run_cli(SINGLE_YEAR.replace("5100", "9999"), "balance") + self.assertEqual(code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_exporter.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_exporter.py new file mode 100644 index 00000000..5478ee92 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_exporter.py @@ -0,0 +1,53 @@ +import json +import unittest +from datetime import date + +from helpers import eur, sample_journal +from ledger import Money, Transaction +from ledger.exporter import format_amount, journal_to_json, transactions_to_csv, trial_balance_to_csv + + +class FormatAmountTests(unittest.TestCase): + def test_styles(self): + value = Money("-1234.5") + self.assertEqual(format_amount(value), "-1234.50") + self.assertEqual(format_amount(value, "parens"), "(1234.50)") + self.assertEqual(format_amount(value, "german"), "-1.234,50") + self.assertEqual(format_amount(Money("1234567.891"), "german"), "1.234.567,89") + self.assertEqual(format_amount(Money("5"), "parens"), "5.00") + + def test_currency_without_minor_units(self): + self.assertEqual(format_amount(Money("1234", "JPY"), "german"), "1.234") + + def test_unknown_style(self): + with self.assertRaises(ValueError): + format_amount(Money("1"), "roman") + + +class CsvTests(unittest.TestCase): + def test_transactions_to_csv(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "Rent, January", "5000", "1000", eur("800.00")) + self.assertEqual( + transactions_to_csv([tx]), + "id,date,description,account,amount,currency\n" + 't1,2024-01-05,"Rent, January",5000,800.00,EUR\n' + 't1,2024-01-05,"Rent, January",1000,-800.00,EUR\n', + ) + + def test_trial_balance_to_csv(self): + lines = trial_balance_to_csv(sample_journal(), date(2024, 1, 31)).splitlines() + self.assertEqual(lines[0], "code,name,debit,credit") + self.assertIn("1000,Bank,5400.00,0.00", lines) + self.assertIn("3000,Owner equity,0.00,5000.00", lines) + + +class JsonTests(unittest.TestCase): + def test_journal_to_json(self): + data = json.loads(journal_to_json(sample_journal())) + self.assertEqual(data["base_currency"], "EUR") + self.assertEqual(len(data["transactions"]), 7) + self.assertEqual(data["transactions"][2]["postings"][0], {"account": "5000", "amount": "800.00", "currency": "EUR"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_fx.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_fx.py new file mode 100644 index 00000000..12d2f233 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_fx.py @@ -0,0 +1,74 @@ +import unittest +from datetime import date +from decimal import Decimal + +from ledger.fx import MissingRate, RateTable +from ledger.money import Money + +DAY = date(2024, 3, 15) + + +class RateTests(unittest.TestCase): + def setUp(self): + self.table = RateTable("EUR") + self.table.set_rate("USD", "1.10", date(2024, 1, 1)) + self.table.set_rate("USD", "1.20", date(2024, 3, 1)) + self.table.set_rate("GBP", "0.85", date(2024, 1, 1)) + + def test_base_rate_is_one(self): + self.assertEqual(self.table.rate("EUR", DAY), Decimal(1)) + + def test_latest_rate_on_or_before_date(self): + self.assertEqual(self.table.rate("USD", date(2024, 2, 29)), Decimal("1.10")) + self.assertEqual(self.table.rate("USD", date(2024, 3, 1)), Decimal("1.20")) + self.assertEqual(self.table.rate("usd", DAY), Decimal("1.20")) + + def test_missing_rates(self): + with self.assertRaises(MissingRate): + self.table.rate("CHF", DAY) + with self.assertRaises(MissingRate): + self.table.rate("USD", date(2023, 12, 31)) + + def test_invalid_rates(self): + with self.assertRaises(ValueError): + self.table.set_rate("EUR", "1", DAY) + with self.assertRaises(ValueError): + self.table.set_rate("CHF", "0", DAY) + + def test_setting_a_rate_twice_replaces_it(self): + self.table.set_rate("USD", "1.25", date(2024, 3, 1)) + self.assertEqual(self.table.rate("USD", DAY), Decimal("1.25")) + + +class ConvertTests(unittest.TestCase): + def setUp(self): + self.table = RateTable("EUR") + self.table.set_rate("USD", "1.10", date(2024, 1, 1)) + self.table.set_rate("GBP", "0.80", date(2024, 1, 1)) + self.table.set_rate("JPY", "160.45", date(2024, 1, 1)) + + def test_from_base(self): + self.assertEqual(self.table.convert(Money("100.00", "EUR"), "USD", DAY), Money("110.00", "USD")) + + def test_to_base(self): + self.assertEqual(self.table.convert(Money("110.00", "USD"), "EUR", DAY), Money("100.00", "EUR")) + + def test_between_two_foreign_currencies(self): + self.assertEqual(self.table.convert(Money("55.00", "USD"), "GBP", DAY), Money("40.00", "GBP")) + self.assertEqual(self.table.cross_rate("USD", "GBP", DAY).quantize(Decimal("0.0001")), Decimal("0.7273")) + + def test_same_currency_is_unchanged(self): + money = Money("12.34", "USD") + self.assertIs(self.table.convert(money, "usd", DAY), money) + + def test_target_without_minor_units(self): + self.assertEqual(self.table.convert(Money("10.00", "EUR"), "JPY", DAY), Money("1604", "JPY")) + + def test_ties_round_half_even(self): + self.table.set_rate("CHF", "1.07", date(2024, 1, 1)) + self.assertEqual(self.table.convert(Money("2.50", "EUR"), "CHF", DAY), Money("2.68", "CHF")) + self.assertEqual(self.table.convert(Money("1.50", "EUR"), "CHF", DAY), Money("1.60", "CHF")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_importer.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_importer.py new file mode 100644 index 00000000..89fb8803 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_importer.py @@ -0,0 +1,129 @@ +import unittest +from datetime import date +from decimal import Decimal + +from ledger import importer +from ledger.importer import ImportFormatError, parse_amount, parse_date + +STATEMENT = """date,description,amount,category +2024-01-05,Opening deposit,"5,000.00",3000 +2024-01-10,Consulting invoice,1200.00,4000 + +2024-01-15,January rent,-800.00,5000 +2024-01-16,Coffee,-3.50, +""" + +GERMAN = """Date;Description;Amount +15.03.2024;Miete;-1.234,50 +16.03.2024;Gehalt;2.500,00 +""" + + +class ParseAmountTests(unittest.TestCase): + def test_plain_numbers(self): + self.assertEqual(parse_amount("12"), Decimal("12")) + self.assertEqual(parse_amount("12.50"), Decimal("12.50")) + self.assertEqual(parse_amount(" 7.05 "), Decimal("7.05")) + + def test_signs(self): + self.assertEqual(parse_amount("-12.50"), Decimal("-12.50")) + self.assertEqual(parse_amount("+12.50"), Decimal("12.50")) + self.assertEqual(parse_amount("12.50-"), Decimal("-12.50")) + + def test_parenthesised_negatives(self): + self.assertEqual(parse_amount("(1,234.50)"), Decimal("-1234.50")) + self.assertEqual(parse_amount("( 12.00 )"), Decimal("-12.00")) + self.assertEqual(parse_amount("($99.99)"), Decimal("-99.99")) + + def test_currency_marks_and_spaces(self): + self.assertEqual(parse_amount("$1,234.50"), Decimal("1234.50")) + self.assertEqual(parse_amount("\u20ac 12,50"), Decimal("12.50")) + self.assertEqual(parse_amount("1 234,50"), Decimal("1234.50")) + self.assertEqual(parse_amount("1\u00a0234,50"), Decimal("1234.50")) + + def test_both_separators(self): + self.assertEqual(parse_amount("1,234.50"), Decimal("1234.50")) + self.assertEqual(parse_amount("1.234,50"), Decimal("1234.50")) + self.assertEqual(parse_amount("1,234,567.89"), Decimal("1234567.89")) + self.assertEqual(parse_amount("1.234.567,89"), Decimal("1234567.89")) + + def test_decimal_comma(self): + self.assertEqual(parse_amount("12,5"), Decimal("12.5")) + self.assertEqual(parse_amount("0,75"), Decimal("0.75")) + self.assertEqual(parse_amount("-1234,5"), Decimal("-1234.5")) + + def test_dot_as_thousands_separator(self): + self.assertEqual(parse_amount("1.234"), Decimal("1234")) + self.assertEqual(parse_amount("1.234.567"), Decimal("1234567")) + self.assertEqual(parse_amount("0.125"), Decimal("0.125")) + + def test_comma_as_thousands_separator(self): + self.assertEqual(parse_amount("1,234"), Decimal("1234")) + self.assertEqual(parse_amount("(12,345)"), Decimal("-12345")) + + def test_rejects_garbage(self): + for text in ("", "abc", "1e5", "--5", "1.2x", "NaN", "(5"): + with self.assertRaises(ValueError, msg=text): + parse_amount(text) + + +class ParseDateTests(unittest.TestCase): + def test_formats(self): + self.assertEqual(parse_date("2024-03-15"), date(2024, 3, 15)) + self.assertEqual(parse_date("15.03.2024"), date(2024, 3, 15)) + self.assertEqual(parse_date("03/15/2024"), date(2024, 3, 15)) + + def test_unknown_format(self): + with self.assertRaises(ValueError): + parse_date("March 15th") + + +class ReadRowsTests(unittest.TestCase): + def test_reads_rows_and_skips_blank_lines(self): + rows = importer.read_rows(STATEMENT) + self.assertEqual(len(rows), 4) + self.assertEqual(rows[0].description, "Opening deposit") + self.assertEqual(rows[0].amount, Decimal("5000.00")) + self.assertEqual(rows[3].category, "") + self.assertEqual(rows[3].line, 6) + + def test_german_file(self): + rows = importer.read_rows(GERMAN, delimiter=";") + self.assertEqual([r.amount for r in rows], [Decimal("-1234.50"), Decimal("2500.00")]) + self.assertEqual(rows[0].date, date(2024, 3, 15)) + + def test_missing_column(self): + with self.assertRaises(ImportFormatError) as ctx: + importer.read_rows("date,amount\n2024-01-01,5\n") + self.assertEqual(ctx.exception.line, 1) + + def test_bad_amount_reports_the_line(self): + with self.assertRaises(ImportFormatError) as ctx: + importer.read_rows("date,description,amount\n2024-01-01,ok,5\n2024-01-02,bad,five\n") + self.assertEqual(ctx.exception.line, 3) + + def test_thousands_with_commas_in_a_file(self): + rows = importer.read_rows('date,description,amount\n2024-01-01,Bonus,"1,500"\n2024-01-02,Car,"(12,345)"\n') + self.assertEqual([r.amount for r in rows], [Decimal("1500"), Decimal("-12345")]) + + +class TransactionTests(unittest.TestCase): + def test_signs_and_default_accounts(self): + txs = importer.load_statement(STATEMENT) + self.assertEqual([tx.id for tx in txs], ["imp-0001", "imp-0002", "imp-0003", "imp-0004"]) + deposit, _invoice, rent, coffee = txs + self.assertEqual([(p.account, str(p.amount.amount)) for p in deposit.postings], + [("1000", "5000.00"), ("3000", "-5000.00")]) + self.assertEqual([(p.account, str(p.amount.amount)) for p in rent.postings], + [("1000", "-800.00"), ("5000", "800.00")]) + self.assertEqual(coffee.postings[1].account, "5900") + + def test_options(self): + txs = importer.load_statement("date,description,amount\n2024-01-01,Gift,10\n", bank="1100", currency="USD", income="4100") + self.assertEqual(txs[0].postings[0].account, "1100") + self.assertEqual(txs[0].postings[1].account, "4100") + self.assertEqual(txs[0].postings[0].amount.currency, "USD") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_journal.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_journal.py new file mode 100644 index 00000000..5f77be5b --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_journal.py @@ -0,0 +1,82 @@ +import unittest +from datetime import date + +from helpers import eur, sample_journal +from ledger import Journal, Money, Transaction, default_chart +from ledger.accounts import UnknownAccount +from ledger.journal import DuplicateTransaction +from ledger.transactions import Posting, UnbalancedTransaction + + +class PostingTests(unittest.TestCase): + def test_post_and_count(self): + self.assertEqual(len(sample_journal()), 7) + + def test_duplicate_id_is_rejected(self): + journal = sample_journal() + again = Transaction.transfer("t1", date(2024, 4, 1), "dup", "1000", "3000", eur("1.00")) + with self.assertRaises(DuplicateTransaction): + journal.post(again) + self.assertEqual(len(journal), 7) + + def test_unknown_account_is_rejected(self): + journal = Journal(default_chart()) + tx = Transaction.transfer("x", date(2024, 1, 1), "bad", "1000", "9999", eur("1.00")) + with self.assertRaises(UnknownAccount): + journal.post(tx) + self.assertEqual(len(journal), 0) + + def test_unbalanced_is_rejected(self): + journal = Journal(default_chart()) + tx = Transaction("x", date(2024, 1, 1), "bad", [Posting("1000", eur("2")), Posting("3000", eur("-1"))]) + with self.assertRaises(UnbalancedTransaction): + journal.post(tx) + + +class QueryTests(unittest.TestCase): + def setUp(self): + self.journal = sample_journal() + + def test_transactions_are_ordered(self): + ids = [tx.id for tx in self.journal.transactions()] + self.assertEqual(ids, ["t1", "t2", "t3", "t4", "t5", "t6", "t7"]) + + def test_date_filter_is_inclusive(self): + found = self.journal.transactions(date(2024, 1, 10), date(2024, 2, 3)) + self.assertEqual([tx.id for tx in found], ["t2", "t3", "t4"]) + + def test_account_filter(self): + found = self.journal.transactions(account="4000") + self.assertEqual([tx.id for tx in found], ["t2", "t5"]) + + def test_balance_as_of_is_inclusive(self): + self.assertEqual(self.journal.balance("1000"), eur("5253.35")) + self.assertEqual(self.journal.balance("1000", date(2024, 1, 15)), eur("5400.00")) + self.assertEqual(self.journal.balance("1000", date(2024, 1, 14)), eur("6200.00")) + + def test_balance_in_other_currency_is_zero(self): + self.assertEqual(self.journal.balance("1000", currency="USD"), Money.zero("USD")) + + def test_natural_balance_flips_credit_accounts(self): + self.assertEqual(self.journal.balance("4000"), eur("-2100.00")) + self.assertEqual(self.journal.natural_balance("4000"), eur("2100.00")) + self.assertEqual(self.journal.natural_balance("5000"), eur("1600.00")) + + def test_movement_in_period(self): + self.assertEqual(self.journal.movement("1000", date(2024, 2, 1), date(2024, 2, 29)), eur("653.35")) + + def test_trial_balance_sums_to_zero(self): + trial = self.journal.trial_balance() + self.assertEqual(sorted(trial), ["1000", "3000", "4000", "5000", "5100", "5200"]) + self.assertEqual(sum((v.amount for v in trial.values())), 0) + + def test_statement_has_running_balance(self): + lines = self.journal.statement("1000") + self.assertEqual([line.tx_id for line in lines], ["t1", "t2", "t3", "t4", "t5", "t6", "t7"]) + self.assertEqual(lines[2].amount, eur("-800.00")) + self.assertEqual(lines[2].balance, eur("5400.00")) + self.assertEqual(lines[-1].balance, eur("5253.35")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_money.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_money.py new file mode 100644 index 00000000..8ca45657 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_money.py @@ -0,0 +1,111 @@ +import unittest +from decimal import Decimal + +from ledger.money import CurrencyMismatch, Money, minor_units + + +def amounts(parts): + return [str(p.amount) for p in parts] + + +class ConstructionTests(unittest.TestCase): + def test_from_str_and_int(self): + self.assertEqual(Money("12.50").amount, Decimal("12.50")) + self.assertEqual(Money(7).amount, Decimal("7")) + + def test_floats_are_rejected(self): + with self.assertRaises(TypeError): + Money(0.1) + + def test_currency_is_upper_cased(self): + self.assertEqual(Money("1", "usd").currency, "USD") + + def test_minor_units(self): + self.assertEqual(minor_units("EUR"), 2) + self.assertEqual(minor_units("jpy"), 0) + self.assertEqual(minor_units("KWD"), 3) + + def test_minor_unit_round_trip(self): + self.assertEqual(Money("12.34").to_minor(), 1234) + self.assertEqual(Money.from_minor(-5), Money("-0.05")) + self.assertEqual(Money("500", "JPY").to_minor(), 500) + self.assertEqual(Money.from_minor(1234, "KWD").amount, Decimal("1.234")) + + def test_sub_unit_amount_has_no_minor_value(self): + with self.assertRaises(ValueError): + Money("0.001").to_minor() + + +class ArithmeticTests(unittest.TestCase): + def test_add_sub_neg_abs(self): + self.assertEqual(Money("1.10") + Money("2.20"), Money("3.30")) + self.assertEqual(Money("1.10") - Money("2.20"), Money("-1.10")) + self.assertEqual(-Money("1.10"), Money("-1.10")) + self.assertEqual(abs(Money("-4.00")), Money("4.00")) + + def test_currency_mismatch(self): + with self.assertRaises(CurrencyMismatch): + Money("1", "EUR") + Money("1", "USD") + with self.assertRaises(CurrencyMismatch): + Money("1", "EUR") < Money("2", "USD") + + def test_comparisons(self): + self.assertTrue(Money("1.00") < Money("1.01")) + self.assertTrue(Money("2.00") >= Money("2.0")) + self.assertFalse(Money("2.00") > Money("2.00")) + + def test_multiply_rounds_to_minor_unit(self): + self.assertEqual(Money("19.99") * Decimal("0.2"), Money("4.00")) + self.assertEqual(3 * Money("0.10"), Money("0.30")) + + def test_multiply_tie_rounds_half_even(self): + self.assertEqual(Money("10.00") * Decimal("0.2675"), Money("2.68")) + self.assertEqual(Money("10.00") * Decimal("0.2665"), Money("2.66")) + + def test_divide(self): + self.assertEqual(Money("10.00") / 3, Money("3.33")) + + def test_str(self): + self.assertEqual(str(Money("1234.5")), "1234.50 EUR") + self.assertEqual(str(Money("-3", "JPY")), "-3 JPY") + + +class AllocateTests(unittest.TestCase): + def test_split_in_three(self): + self.assertEqual(amounts(Money("100.00").split(3)), ["33.34", "33.33", "33.33"]) + + def test_allocate_by_ratio(self): + self.assertEqual(amounts(Money("100.00").allocate([70, 30])), ["70.00", "30.00"]) + self.assertEqual(amounts(Money("0.05").allocate([3, 7])), ["0.02", "0.03"]) + + def test_leftover_goes_to_first_parts_not_largest_remainder(self): + self.assertEqual(amounts(Money("0.07").allocate([3, 1, 6])), ["0.03", "0.00", "0.04"]) + + def test_zero_ratio_gets_nothing(self): + self.assertEqual(amounts(Money("0.01").allocate([0, 1, 1])), ["0.00", "0.01", "0.00"]) + + def test_parts_always_add_up(self): + for cents in (1, 2, 99, 100, 101, 12345): + for ratios in ([1, 1], [1, 1, 1], [5, 3, 2], [1, 2, 3, 4, 5]): + parts = Money.from_minor(cents).allocate(ratios) + self.assertEqual(sum((p.amount for p in parts), Decimal(0)), Decimal(cents) / 100) + + def test_split_without_minor_units(self): + self.assertEqual(amounts(Money("100", "JPY").split(3)), ["34", "33", "33"]) + + def test_negative_amount_split(self): + self.assertEqual(amounts(Money("-100.00").split(3)), ["-33.34", "-33.33", "-33.33"]) + + def test_invalid_arguments(self): + with self.assertRaises(ValueError): + Money("1.00").allocate([]) + with self.assertRaises(ValueError): + Money("1.00").allocate([0, 0]) + with self.assertRaises(ValueError): + Money("1.00").allocate([1, -1]) + with self.assertRaises(ValueError): + Money("1.00").split(0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_reports.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_reports.py new file mode 100644 index 00000000..58d337c1 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_reports.py @@ -0,0 +1,68 @@ +import unittest +from datetime import date + +from helpers import eur, sample_journal, two_year_journal +from ledger import reports + + +class MonthlyTotalsTests(unittest.TestCase): + def test_bank_by_month(self): + totals = reports.monthly_totals(sample_journal(), "1000") + self.assertEqual(list(totals), [date(2024, 1, 1), date(2024, 2, 1), date(2024, 3, 1)]) + self.assertEqual(totals[date(2024, 1, 1)], eur("5400.00")) + self.assertEqual(totals[date(2024, 2, 1)], eur("653.35")) + self.assertEqual(totals[date(2024, 3, 1)], eur("-800.00")) + + def test_period_limits(self): + totals = reports.monthly_totals(sample_journal(), "1000", date(2024, 2, 1), date(2024, 2, 29)) + self.assertEqual(list(totals), [date(2024, 2, 1)]) + + def test_income_account_is_negative(self): + totals = reports.monthly_totals(sample_journal(), "4000") + self.assertEqual(totals[date(2024, 1, 1)], eur("-1200.00")) + + def test_same_month_in_different_years_is_not_merged(self): + totals = reports.monthly_totals(two_year_journal(), "1000") + self.assertEqual(list(totals), [date(2023, 1, 1), date(2023, 12, 1), date(2024, 1, 1)]) + self.assertEqual(totals[date(2023, 1, 1)], eur("2000.00")) + self.assertEqual(totals[date(2024, 1, 1)], eur("1500.00")) + + def test_year_boundary_months_stay_separate(self): + totals = reports.monthly_totals(two_year_journal(), "4000", date(2023, 12, 1), date(2024, 1, 31)) + self.assertEqual(totals[date(2023, 12, 1)], eur("-2100.00")) + self.assertEqual(totals[date(2024, 1, 1)], eur("-2200.00")) + + +class StatementReportTests(unittest.TestCase): + def test_income_statement(self): + result = reports.income_statement(sample_journal(), date(2024, 1, 1), date(2024, 3, 31)) + self.assertEqual(result.income, eur("2100.00")) + self.assertEqual(result.expenses, eur("1846.65")) + self.assertEqual(result.net, eur("253.35")) + self.assertEqual(result.by_account["5000"], eur("1600.00")) + + def test_income_statement_for_one_month(self): + result = reports.income_statement(sample_journal(), date(2024, 2, 1), date(2024, 2, 29)) + self.assertEqual(result.income, eur("900.00")) + self.assertEqual(sorted(result.by_account), ["4000", "5100", "5200"]) + + def test_balance_sheet_balances(self): + sheet = reports.balance_sheet(sample_journal(), date(2024, 3, 31)) + self.assertEqual(sheet["assets"], eur("5253.35")) + self.assertEqual(sheet["liabilities"], eur("0.00")) + self.assertEqual(sheet["equity"], eur("5253.35")) + self.assertEqual(sheet["assets"], sheet["liabilities"] + sheet["equity"]) + + def test_trial_balance_rows(self): + rows = reports.trial_balance_rows(sample_journal(), date(2024, 1, 31)) + by_code = {code: (debit, credit) for code, _name, debit, credit in rows} + self.assertEqual(by_code["1000"], (eur("5400.00"), eur("0"))) + self.assertEqual(by_code["3000"], (eur("0"), eur("5000.00"))) + + def test_top_expenses(self): + top = reports.top_expenses(sample_journal(), date(2024, 1, 1), date(2024, 3, 31), limit=2) + self.assertEqual(top, [("5000", eur("1600.00")), ("5100", eur("150.25"))]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_rounding.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_rounding.py new file mode 100644 index 00000000..e093c302 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_rounding.py @@ -0,0 +1,60 @@ +import unittest +from decimal import Decimal + +from ledger.rounding import quantum, round_decimal, round_half_even, round_to_increment + + +class QuantumTests(unittest.TestCase): + def test_quantum_values(self): + self.assertEqual(quantum(2), Decimal("0.01")) + self.assertEqual(quantum(0), Decimal("1")) + self.assertEqual(quantum(3), Decimal("0.001")) + + +class HalfEvenTests(unittest.TestCase): + def test_ties_go_to_even_digit(self): + self.assertEqual(round_half_even(Decimal("0.125")), Decimal("0.12")) + self.assertEqual(round_half_even(Decimal("0.135")), Decimal("0.14")) + self.assertEqual(round_half_even(Decimal("0.145")), Decimal("0.14")) + + def test_ties_that_floats_cannot_represent(self): + self.assertEqual(round_half_even(Decimal("2.675")), Decimal("2.68")) + self.assertEqual(round_half_even(Decimal("1.015")), Decimal("1.02")) + + def test_not_a_tie(self): + self.assertEqual(round_half_even(Decimal("2.6751")), Decimal("2.68")) + self.assertEqual(round_half_even(Decimal("2.6749")), Decimal("2.67")) + + def test_result_has_requested_places(self): + self.assertEqual(str(round_half_even(Decimal("3"), 2)), "3.00") + self.assertEqual(str(round_half_even(Decimal("2.5"), 0)), "2") + + +class RoundDecimalTests(unittest.TestCase): + def test_modes(self): + value = Decimal("2.675") + self.assertEqual(round_decimal(value, 2, "half_up"), Decimal("2.68")) + self.assertEqual(round_decimal(value, 2, "down"), Decimal("2.67")) + self.assertEqual(round_decimal(value, 2, "up"), Decimal("2.68")) + self.assertEqual(round_decimal(Decimal("-2.671"), 2, "floor"), Decimal("-2.68")) + self.assertEqual(round_decimal(Decimal("-2.679"), 2, "ceiling"), Decimal("-2.67")) + + def test_unknown_mode(self): + with self.assertRaises(ValueError): + round_decimal(Decimal("1.00"), 2, "sideways") + + +class IncrementTests(unittest.TestCase): + def test_cash_rounding(self): + step = Decimal("0.05") + self.assertEqual(round_to_increment(Decimal("1.02"), step), Decimal("1.00")) + self.assertEqual(round_to_increment(Decimal("1.03"), step), Decimal("1.05")) + self.assertEqual(round_to_increment(Decimal("1.075"), step, "down"), Decimal("1.05")) + + def test_increment_must_be_positive(self): + with self.assertRaises(ValueError): + round_to_increment(Decimal("1"), Decimal("0")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_transactions.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_transactions.py new file mode 100644 index 00000000..27149d2e --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_transactions.py @@ -0,0 +1,91 @@ +import unittest +from datetime import date + +from helpers import eur +from ledger.money import Money +from ledger.transactions import Posting, Transaction, UnbalancedTransaction + + +class TransferTests(unittest.TestCase): + def test_transfer_postings(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "Pay rent", "5000", "1000", eur("800.00")) + self.assertEqual([p.account for p in tx.postings], ["5000", "1000"]) + self.assertEqual(tx.postings[0].amount, eur("800.00")) + self.assertEqual(tx.postings[1].amount, eur("-800.00")) + self.assertTrue(tx.is_balanced()) + + def test_date_may_be_an_iso_string(self): + tx = Transaction("t1", "2024-02-29", "x", [Posting("1", eur("1")), Posting("2", eur("-1"))]) + self.assertEqual(tx.date, date(2024, 2, 29)) + + def test_accounts_are_distinct_in_order(self): + tx = Transaction("t1", date(2024, 1, 1), "x", [ + Posting("5000", eur("3")), Posting("1000", eur("-1")), Posting("5000", eur("-2")), + ]) + self.assertEqual(tx.accounts(), ["5000", "1000"]) + self.assertEqual(tx.amount_for("5000"), eur("1")) + + +class ValidationTests(unittest.TestCase): + def test_unbalanced_is_rejected(self): + tx = Transaction("t1", date(2024, 1, 1), "x", [Posting("1", eur("10.00")), Posting("2", eur("-9.99"))]) + self.assertFalse(tx.is_balanced()) + with self.assertRaises(UnbalancedTransaction) as ctx: + tx.validate() + self.assertIn("0.01 EUR", str(ctx.exception)) + + def test_needs_two_postings(self): + tx = Transaction("t1", date(2024, 1, 1), "x", [Posting("1", eur("0"))]) + with self.assertRaises(ValueError): + tx.validate() + + def test_balance_is_checked_per_currency(self): + usd = lambda text: Money(text, "USD") + balanced = Transaction("t1", date(2024, 1, 1), "x", [ + Posting("1", eur("10")), Posting("2", eur("-10")), Posting("3", usd("5")), Posting("4", usd("-5")), + ]) + crossed = Transaction("t2", date(2024, 1, 1), "x", [Posting("1", eur("10")), Posting("2", usd("-10"))]) + self.assertTrue(balanced.is_balanced()) + self.assertEqual(sorted(crossed.imbalance()), ["EUR", "USD"]) + + +class ReversalTests(unittest.TestCase): + def test_reversed_negates_postings(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "Pay rent", "5000", "1000", eur("800.00"), tags=["rent"]) + undo = tx.reversed("t1-r", date(2024, 1, 9)) + self.assertEqual(undo.id, "t1-r") + self.assertEqual(undo.date, date(2024, 1, 9)) + self.assertEqual(undo.description, "Reversal of Pay rent") + self.assertEqual(undo.postings[0].amount, eur("-800.00")) + self.assertEqual(undo.tags, ["rent"]) + self.assertIsNot(undo.tags, tx.tags) + + def test_reversal_defaults_to_same_date(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "x", "5000", "1000", eur("1.00")) + self.assertEqual(tx.reversed("t1-r").date, date(2024, 1, 5)) + + +class SplitTests(unittest.TestCase): + def test_split_evenly(self): + tx = Transaction.from_split( + "s1", date(2024, 3, 1), "Shared bill", "1000", {"5000": 1, "5100": 1, "5200": 1}, eur("100.00"), + ) + self.assertEqual([str(p.amount.amount) for p in tx.postings], ["33.34", "33.33", "33.33", "-100.00"]) + self.assertTrue(tx.is_balanced()) + + def test_split_by_ratio_gives_extra_cents_to_first_targets(self): + tx = Transaction.from_split( + "s2", date(2024, 3, 1), "Tip", "1000", {"5000": 3, "5100": 1, "5200": 6}, eur("0.07"), + ) + self.assertEqual([str(p.amount.amount) for p in tx.postings], ["0.03", "0.00", "0.04", "-0.07"]) + + def test_refund_split_stays_balanced(self): + tx = Transaction.from_split( + "s3", date(2024, 3, 1), "Refund", "1000", {"5000": 1, "5100": 1, "5200": 1}, eur("-100.00"), + ) + self.assertTrue(tx.is_balanced()) + self.assertEqual([str(p.amount.amount) for p in tx.postings[:3]], ["-33.34", "-33.33", "-33.33"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_utils.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_utils.py new file mode 100644 index 00000000..72c4b756 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/pristine_tests/test_utils.py @@ -0,0 +1,53 @@ +import unittest +from datetime import date + +from ledger import utils + + +class ChunkedTests(unittest.TestCase): + def test_chunks_of_three(self): + self.assertEqual(list(utils.chunked([1, 2, 3, 4, 5, 6, 7], 3)), [[1, 2, 3], [4, 5, 6], [7]]) + + def test_size_must_be_positive(self): + with self.assertRaises(ValueError): + list(utils.chunked([1], 0)) + + +class GroupByTests(unittest.TestCase): + def test_keeps_first_seen_order(self): + groups = utils.group_by(["bb", "a", "cc", "d", "e"], len) + self.assertEqual(list(groups), [2, 1]) + self.assertEqual(groups[1], ["a", "d", "e"]) + + +class DateHelperTests(unittest.TestCase): + def test_ensure_date(self): + self.assertEqual(utils.ensure_date("2024-03-09"), date(2024, 3, 9)) + self.assertEqual(utils.ensure_date(date(2024, 3, 9)), date(2024, 3, 9)) + + def test_add_months_clamps_day(self): + self.assertEqual(utils.add_months(date(2024, 1, 31), 1), date(2024, 2, 29)) + self.assertEqual(utils.add_months(date(2023, 1, 31), 1), date(2023, 2, 28)) + + def test_add_months_crosses_years(self): + self.assertEqual(utils.add_months(date(2023, 11, 15), 3), date(2024, 2, 15)) + self.assertEqual(utils.add_months(date(2024, 2, 15), -3), date(2023, 11, 15)) + + def test_month_boundaries(self): + self.assertEqual(utils.first_of_month(date(2024, 2, 17)), date(2024, 2, 1)) + self.assertEqual(utils.last_of_month(date(2024, 2, 17)), date(2024, 2, 29)) + self.assertEqual(utils.last_of_month(date(2023, 12, 3)), date(2023, 12, 31)) + + def test_daterange_is_inclusive(self): + days = list(utils.daterange(date(2024, 2, 27), date(2024, 3, 1))) + self.assertEqual(len(days), 4) + self.assertEqual(days[-1], date(2024, 3, 1)) + + def test_clamp(self): + self.assertEqual(utils.clamp(5, 1, 3), 3) + self.assertEqual(utils.clamp(-5, 1, 3), 1) + self.assertEqual(utils.clamp(2, 1, 3), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/hidden/test_hidden.py b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/test_hidden.py new file mode 100644 index 00000000..f92bd9ef --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/hidden/test_hidden.py @@ -0,0 +1,254 @@ +"""Extra cases for the bug classes behind the visible failures.""" + +import unittest +from datetime import date, timedelta +from decimal import Decimal + +from ledger import Account, AccountKind, Chart, Journal, Money, Transaction, default_chart +from ledger.calendar import BusinessCalendar +from ledger.fx import RateTable +from ledger.importer import load_statement, parse_amount +from ledger.reports import monthly_totals +from ledger.rounding import round_decimal, round_half_even, round_to_increment + +D = Decimal + + +def minor(parts): + return [p.to_minor() for p in parts] + + +class AllocateNegative(unittest.TestCase): + def test_one_cent_split_three_ways(self): + self.assertEqual(minor(Money("-0.01").split(3)), [-1, 0, 0]) + self.assertEqual(minor(Money("0.01").split(3)), [1, 0, 0]) + + def test_parts_add_up_for_many_amounts(self): + for cents in list(range(-300, 301, 7)) + [-9999, 12345, -100001]: + for ratios in ([2, 3, 5], [1, 1, 1], [7, 0, 3], [1, 2, 3, 4, 5, 6, 7]): + parts = Money.from_minor(cents).allocate(ratios) + self.assertEqual(sum(minor(parts)), cents, (cents, ratios)) + self.assertEqual(len(parts), len(ratios)) + + def test_negative_mirrors_positive(self): + for cents in (1, 7, 100, 1001, 99999): + for ratios in ([3, 1, 6], [1, 1, 1], [5, 3, 2]): + positive = minor(Money.from_minor(cents).allocate(ratios)) + negative = minor(Money.from_minor(-cents).allocate(ratios)) + self.assertEqual(negative, [-x for x in positive], (cents, ratios)) + + def test_policy_for_negative_amounts(self): + self.assertEqual(minor(Money("-0.07").allocate([3, 1, 6])), [-3, 0, -4]) + self.assertEqual(minor(Money("-0.01").allocate([0, 1, 1])), [0, -1, 0]) + + def test_negative_without_minor_units(self): + self.assertEqual(minor(Money("-100", "JPY").split(3)), [-34, -33, -33]) + self.assertEqual(minor(Money("-1.000", "KWD").split(3)), [-334, -333, -333]) + + def test_positive_behaviour_is_unchanged(self): + self.assertEqual(minor(Money("100.00").allocate([1, 1, 1])), [3334, 3333, 3333]) + self.assertEqual(minor(Money("0.05").allocate([3, 7])), [2, 3]) + self.assertEqual(minor(Money("0.00").split(4)), [0, 0, 0, 0]) + + def test_refund_split_in_a_journal(self): + journal = Journal(default_chart()) + tx = Transaction.from_split( + "r1", date(2024, 5, 3), "Refund", "1000", {"5000": 2, "5100": 1, "5200": 1}, Money("-10.01"), + ) + journal.post(tx) + self.assertEqual(journal.balance("1000"), Money("10.01")) + self.assertEqual(sum(journal.balance(c).amount for c in ("5000", "5100", "5200")), D("-10.01")) + + +class RoundingTies(unittest.TestCase): + def test_tie_table(self): + expected = { + "0.005": "0.00", "0.015": "0.02", "0.025": "0.02", "0.065": "0.06", "0.075": "0.08", + "0.155": "0.16", "0.175": "0.18", "0.235": "0.24", "1.005": "1.00", "2.675": "2.68", + "-0.015": "-0.02", "-0.025": "-0.02", "-2.675": "-2.68", "10.125": "10.12", "10.135": "10.14", + } + for text, want in expected.items(): + self.assertEqual(str(round_half_even(D(text))), want, text) + + def test_other_places(self): + self.assertEqual(str(round_half_even(D("1.0005"), 3)), "1.000") + self.assertEqual(str(round_half_even(D("1.0015"), 3)), "1.002") + self.assertEqual(str(round_half_even(D("0.5"), 0)), "0") + self.assertEqual(str(round_half_even(D("1.5"), 0)), "2") + self.assertEqual(str(round_half_even(D("2.5"), 0)), "2") + + def test_large_values_keep_every_digit(self): + self.assertEqual(str(round_half_even(D("12345678901234567.125"))), "12345678901234567.12") + self.assertEqual(str(round_half_even(D("12345678901234567.135"))), "12345678901234567.14") + + def test_not_quite_ties(self): + self.assertEqual(str(round_half_even(D("0.1250000000000000000001"))), "0.13") + self.assertEqual(str(round_half_even(D("0.1249999999999999999999"))), "0.12") + + def test_round_decimal_default_mode(self): + self.assertEqual(round_decimal(D("0.025")), D("0.02")) + self.assertEqual(round_decimal(D("0.025"), 2, "half_up"), D("0.03")) + + def test_increment_ties(self): + step = D("0.05") + self.assertEqual(round_to_increment(D("1.025"), step), D("1.00")) + self.assertEqual(round_to_increment(D("1.075"), step), D("1.10")) + + def test_money_and_fx_use_the_same_rounding(self): + self.assertEqual(Money("1.50") * D("1.07"), Money("1.60")) + self.assertEqual(Money("10.00") * D("0.0025"), Money("0.02")) + self.assertEqual(Money("10.00") * D("0.0075"), Money("0.08")) + table = RateTable("EUR") + table.set_rate("USD", "1.07", date(2024, 1, 1)) + day = date(2024, 2, 1) + self.assertEqual(table.convert(Money("2.50"), "USD", day), Money("2.68", "USD")) + self.assertEqual(table.convert(Money("0.50"), "USD", day), Money("0.54", "USD")) + self.assertEqual(table.convert(Money("1.50"), "USD", day), Money("1.60", "USD")) + + +class AccountLabelState(unittest.TestCase): + def test_default_labels_are_not_shared(self): + accounts = [Account(str(i), "A%d" % i, AccountKind.ASSET) for i in range(4)] + accounts[0].add_label("x") + accounts[2].add_label("y") + self.assertEqual([a.labels for a in accounts], [["x"], [], ["y"], []]) + self.assertIsNot(accounts[1].labels, accounts[3].labels) + + def test_labels_argument_is_copied(self): + source = ["cash"] + account = Account("1", "Bank", AccountKind.ASSET, source) + account.add_label("main") + self.assertEqual(source, ["cash"]) + self.assertEqual(account.labels, ["cash", "main"]) + + def test_labels_none_and_tuple(self): + self.assertEqual(Account("1", "A", AccountKind.ASSET, None).labels, []) + account = Account("2", "B", AccountKind.ASSET, ("p", "q")) + account.add_label("r") + self.assertEqual(account.labels, ["p", "q", "r"]) + + def test_default_chart_accounts_are_independent(self): + chart = default_chart() + chart.get("1000").add_label("liquid") + self.assertEqual([a.code for a in chart.by_label("liquid")], ["1000"]) + self.assertEqual(default_chart().by_label("liquid"), []) + fresh = Chart([Account("9", "Z", AccountKind.EQUITY)]) + self.assertEqual(fresh.by_label("liquid"), []) + + +class BusinessDayStarts(unittest.TestCase): + def setUp(self): + self.cal = BusinessCalendar.for_years([2024, 2025]) + + def test_forward_from_weekend(self): + saturday, sunday = date(2024, 3, 2), date(2024, 3, 3) + self.assertEqual(self.cal.add_business_days(saturday, 1), date(2024, 3, 4)) + self.assertEqual(self.cal.add_business_days(sunday, 1), date(2024, 3, 4)) + self.assertEqual(self.cal.add_business_days(saturday, 5), date(2024, 3, 8)) + self.assertEqual(self.cal.add_business_days(sunday, 6), date(2024, 3, 11)) + + def test_zero_returns_the_start(self): + for d in (date(2024, 3, 2), date(2024, 3, 3), date(2024, 5, 1), date(2024, 3, 6)): + self.assertEqual(self.cal.add_business_days(d, 0), d) + + def test_backward_from_weekend(self): + self.assertEqual(self.cal.add_business_days(date(2024, 3, 2), -1), date(2024, 3, 1)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 3), -1), date(2024, 3, 1)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 3), -2), date(2024, 2, 29)) + + def test_from_holidays(self): + self.assertEqual(self.cal.add_business_days(date(2024, 12, 25), 1), date(2024, 12, 27)) + self.assertEqual(self.cal.add_business_days(date(2024, 12, 26), 1), date(2024, 12, 27)) + self.assertEqual(self.cal.add_business_days(date(2024, 12, 25), -1), date(2024, 12, 24)) + self.assertEqual(self.cal.add_business_days(date(2025, 1, 1), 1), date(2025, 1, 2)) + + def test_custom_holiday_on_monday(self): + cal = BusinessCalendar([date(2024, 4, 1)]) + self.assertEqual(cal.add_business_days(date(2024, 3, 30), 1), date(2024, 4, 2)) + self.assertEqual(cal.add_business_days(date(2024, 3, 29), 1), date(2024, 4, 2)) + self.assertEqual(cal.add_business_days(date(2024, 4, 1), 1), date(2024, 4, 2)) + + def test_distance_and_addition_agree(self): + start = date(2024, 11, 20) + for offset in range(0, 70): + first = start + timedelta(days=offset) + for n in range(1, 9): + result = self.cal.add_business_days(first, n) + self.assertTrue(self.cal.is_business_day(result), (first, n)) + self.assertEqual(self.cal.business_days_between(first, result), n, (first, n)) + + def test_business_day_arithmetic_is_consistent_for_business_starts(self): + start = self.cal.next_business_day(date(2024, 11, 20)) + for n in range(-10, 11): + there = self.cal.add_business_days(start, n) + self.assertEqual(self.cal.add_business_days(there, -n), start, n) + + +class MonthlyReportYears(unittest.TestCase): + def build(self, rows): + journal = Journal(default_chart()) + for number, (day, amount) in enumerate(rows): + journal.post(Transaction.transfer("m%d" % number, day, "x", "1000", "4000", Money(amount))) + return journal + + def test_three_years_of_march(self): + journal = self.build([(date(2022, 3, 4), "10"), (date(2023, 3, 5), "20"), (date(2024, 3, 6), "30")]) + totals = monthly_totals(journal, "1000") + self.assertEqual( + list(totals.items()), + [(date(2022, 3, 1), Money("10")), (date(2023, 3, 1), Money("20")), (date(2024, 3, 1), Money("30"))], + ) + + def test_posted_out_of_order(self): + journal = self.build([(date(2024, 1, 9), "5"), (date(2023, 1, 9), "7"), (date(2023, 6, 1), "11"), (date(2024, 6, 2), "13")]) + totals = monthly_totals(journal, "1000") + self.assertEqual(list(totals), [date(2023, 1, 1), date(2023, 6, 1), date(2024, 1, 1), date(2024, 6, 1)]) + self.assertEqual(totals[date(2024, 6, 1)], Money("13")) + + def test_range_filter_across_years(self): + journal = self.build([(date(2022, 2, 1), "1"), (date(2023, 2, 1), "2"), (date(2024, 2, 1), "4"), (date(2024, 2, 20), "8")]) + totals = monthly_totals(journal, "1000", date(2023, 1, 1), date(2024, 12, 31)) + self.assertEqual(totals, {date(2023, 2, 1): Money("2"), date(2024, 2, 1): Money("12")}) + + def test_single_year_behaviour_is_unchanged(self): + journal = self.build([(date(2024, 1, 31), "1"), (date(2024, 2, 1), "2"), (date(2024, 2, 29), "3")]) + totals = monthly_totals(journal, "1000") + self.assertEqual(totals, {date(2024, 1, 1): Money("1"), date(2024, 2, 1): Money("5")}) + + +class SeparatorHandling(unittest.TestCase): + def test_commas_that_group_thousands(self): + cases = { + "1,234": "1234", "12,345": "12345", "123,456": "123456", "1,234,567": "1234567", + "(1,234)": "-1234", "-1,234": "-1234", "\u20ac1,234": "1234", "1,234-": "-1234", + } + for text, want in cases.items(): + self.assertEqual(parse_amount(text), D(want), text) + + def test_commas_that_are_decimal_marks(self): + cases = {"1,5": "1.5", "12,34": "12.34", "0,125": "0.125", "1,2345": "1.2345", "1234,567": "1234.567", "-0,99": "-0.99"} + for text, want in cases.items(): + self.assertEqual(parse_amount(text), D(want), text) + + def test_mixed_notation_still_works(self): + cases = { + "1,234.5": "1234.5", "1.234,5": "1234.5", "12.345.678,9": "12345678.9", "(1.234,50)": "-1234.50", + "1 234 567,89": "1234567.89", "12.5": "12.5", "1.234": "1234", "100": "100", + } + for text, want in cases.items(): + self.assertEqual(parse_amount(text), D(want), text) + + def test_statement_with_quoted_thousands(self): + text = 'date,description,amount\n2024-03-01,Bonus,"2,500"\n2024-03-02,Fee,"(1,250)"\n' + first, second = load_statement(text) + self.assertEqual(first.postings[0].amount, Money("2500")) + self.assertEqual(second.postings[0].amount, Money("-1250")) + + def test_invalid_amounts_still_rejected(self): + for text in ("", "()", "1,2,3x", "-", "abc", "1e3"): + with self.assertRaises(ValueError, msg=text): + parse_amount(text) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/accounts.py b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/accounts.py new file mode 100644 index 00000000..11fb38ef --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/accounts.py @@ -0,0 +1,102 @@ +"""Accounts and the chart of accounts.""" + +from __future__ import annotations + +from enum import Enum +from typing import Dict, Iterable, Iterator, List, Optional + + +class AccountKind(Enum): + ASSET = "asset" + LIABILITY = "liability" + EQUITY = "equity" + INCOME = "income" + EXPENSE = "expense" + + @property + def normal_side(self) -> str: + """The side on which the account normally grows.""" + if self in (AccountKind.ASSET, AccountKind.EXPENSE): + return "debit" + return "credit" + + +class UnknownAccount(KeyError): + """Raised when an account code is not in the chart.""" + + +class DuplicateAccount(ValueError): + """Raised when an account code is added twice.""" + + +class Account: + def __init__(self, code: str, name: str, kind: AccountKind, labels: Optional[Iterable[str]] = None) -> None: + self.code = code + self.name = name + self.kind = kind + self.labels: List[str] = list(labels or []) + + def add_label(self, label: str) -> None: + if label not in self.labels: + self.labels.append(label) + + def has_label(self, label: str) -> bool: + return label in self.labels + + def __repr__(self) -> str: + return "Account(%r, %r, %s)" % (self.code, self.name, self.kind.name) + + +class Chart: + """A chart of accounts, indexed by account code.""" + + def __init__(self, accounts: Iterable[Account] = ()) -> None: + self._accounts: Dict[str, Account] = {} + for account in accounts: + self.add(account) + + def add(self, account: Account) -> Account: + if account.code in self._accounts: + raise DuplicateAccount(account.code) + self._accounts[account.code] = account + return account + + def get(self, code: str) -> Account: + try: + return self._accounts[code] + except KeyError: + raise UnknownAccount(code) from None + + def __contains__(self, code: object) -> bool: + return code in self._accounts + + def __len__(self) -> int: + return len(self._accounts) + + def __iter__(self) -> Iterator[Account]: + for code in sorted(self._accounts): + yield self._accounts[code] + + def by_kind(self, kind: AccountKind) -> List[Account]: + return [a for a in self if a.kind is kind] + + def by_label(self, label: str) -> List[Account]: + return [a for a in self if a.has_label(label)] + + +def default_chart() -> Chart: + """The chart used by the command line tool.""" + rows = [ + ("1000", "Bank", AccountKind.ASSET), + ("1100", "Receivables", AccountKind.ASSET), + ("2000", "Payables", AccountKind.LIABILITY), + ("3000", "Owner equity", AccountKind.EQUITY), + ("4000", "Sales", AccountKind.INCOME), + ("4100", "Interest income", AccountKind.INCOME), + ("4900", "Other income", AccountKind.INCOME), + ("5000", "Rent", AccountKind.EXPENSE), + ("5100", "Groceries", AccountKind.EXPENSE), + ("5200", "Utilities", AccountKind.EXPENSE), + ("5900", "Other expenses", AccountKind.EXPENSE), + ] + return Chart(Account(code, name, kind) for code, name, kind in rows) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/calendar.py b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/calendar.py new file mode 100644 index 00000000..ca9b32c0 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/calendar.py @@ -0,0 +1,78 @@ +"""Business-day arithmetic with a holiday list.""" + +from __future__ import annotations + +import datetime as dt +from typing import FrozenSet, Iterable, Set + + +def fixed_holidays(year: int) -> Set[dt.date]: + """Fixed-date public holidays: New Year, Labour Day, Christmas and Boxing Day.""" + return {dt.date(year, 1, 1), dt.date(year, 5, 1), dt.date(year, 12, 25), dt.date(year, 12, 26)} + + +class BusinessCalendar: + """Knows which days are business days: not a weekend day and not a holiday.""" + + def __init__(self, holidays: Iterable[dt.date] = (), weekend: Iterable[int] = (5, 6)) -> None: + self.holidays: FrozenSet[dt.date] = frozenset(holidays) + self.weekend: FrozenSet[int] = frozenset(weekend) + + @classmethod + def for_years(cls, years: Iterable[int]) -> "BusinessCalendar": + holidays: Set[dt.date] = set() + for year in years: + holidays |= fixed_holidays(year) + return cls(holidays) + + def is_business_day(self, d: dt.date) -> bool: + return d.weekday() not in self.weekend and d not in self.holidays + + def next_business_day(self, d: dt.date) -> dt.date: + """``d`` itself if it is a business day, otherwise the next one.""" + while not self.is_business_day(d): + d += dt.timedelta(days=1) + return d + + def previous_business_day(self, d: dt.date) -> dt.date: + """``d`` itself if it is a business day, otherwise the previous one.""" + while not self.is_business_day(d): + d -= dt.timedelta(days=1) + return d + + def add_business_days(self, d: dt.date, n: int) -> dt.date: + """Move ``n`` business days forward (backward for negative ``n``). + + Each step goes to the next business day strictly after (before) the + current date, so starting on a weekend or holiday is fine: Saturday + plus one business day is Monday. ``n == 0`` returns ``d`` unchanged. + """ + step = dt.timedelta(days=1 if n >= 0 else -1) + current = d + remaining = abs(n) + while remaining: + current += step + if self.is_business_day(current): + remaining -= 1 + return current + + def business_days_between(self, start: dt.date, end: dt.date) -> int: + """Number of business days after ``start`` up to and including ``end`` (negative if ``end`` is earlier).""" + if end < start: + return -self.business_days_between(end, start) + count = 0 + current = start + while current < end: + current += dt.timedelta(days=1) + if self.is_business_day(current): + count += 1 + return count + + def business_days_in_month(self, year: int, month: int) -> int: + count = 0 + current = dt.date(year, month, 1) + while current.month == month: + if self.is_business_day(current): + count += 1 + current += dt.timedelta(days=1) + return count diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/importer.py b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/importer.py new file mode 100644 index 00000000..43c78880 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/importer.py @@ -0,0 +1,162 @@ +"""Import bank statements from CSV text.""" + +from __future__ import annotations + +import csv +import datetime as dt +import io +import re +from dataclasses import dataclass +from decimal import Decimal, InvalidOperation +from typing import List, Optional + +from .money import Money +from .transactions import Transaction + +_CURRENCY_MARKS = "\u20ac$\u00a3" +_NUMERIC = re.compile(r"[0-9.,]*[0-9][0-9.,]*") +_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%m/%d/%Y") + + +class ImportFormatError(ValueError): + """Raised for malformed statement files; ``line`` is the 1-based line number.""" + + def __init__(self, line: int, message: str) -> None: + super().__init__("line %d: %s" % (line, message)) + self.line = line + + +@dataclass(frozen=True) +class StatementRow: + line: int + date: dt.date + description: str + amount: Decimal + category: str + + +def _lone_mark(s: str, mark: str) -> Optional[str]: + """Decide what the only kind of separator in ``s`` means. + + Returns ``mark`` if it is a decimal mark and ``None`` if it only groups + thousands. A mark that repeats, or that is followed by exactly three digits + after a leading group of one to three digits ("1,234", "12.345"), groups + thousands; anything else ("12,5", "0.125", "1234.567") is a decimal mark. + """ + if s.count(mark) > 1: + return None + head, _, tail = s.partition(mark) + if len(tail) == 3 and 1 <= len(head) <= 3 and head != "0": + return None + return mark + + +def _normalise_separators(s: str) -> str: + """Rewrite ``s`` with no grouping separators and at most one ``.`` as decimal mark.""" + last_dot, last_comma = s.rfind("."), s.rfind(",") + if last_dot < 0 and last_comma < 0: + return s + if last_dot >= 0 and last_comma >= 0: + decimal_mark: Optional[str] = "." if last_dot > last_comma else "," + else: + decimal_mark = _lone_mark(s, "." if last_dot >= 0 else ",") + if decimal_mark is None: + return s.replace(".", "").replace(",", "") + head, _, tail = s.rpartition(decimal_mark) + return head.replace(".", "").replace(",", "") + "." + tail + + +def parse_amount(text: str) -> Decimal: + """Parse an amount as it appears in a bank statement. + + Handles a leading or trailing minus, accounting-style negatives in + parentheses ("(1,234.50)"), currency marks, spaces as thousands + separators, and both "1,234.50" and "1.234,50" notation. + """ + s = text.strip() + negative = False + if s.startswith("(") and s.endswith(")"): + negative = True + s = s[1:-1].strip() + for mark in _CURRENCY_MARKS: + s = s.replace(mark, "") + s = s.replace("\u00a0", "").replace(" ", "") + if s.endswith("-"): + negative = True + s = s[:-1] + elif s.startswith("-"): + negative = True + s = s[1:] + elif s.startswith("+"): + s = s[1:] + if not _NUMERIC.fullmatch(s): + raise ValueError("not an amount: %r" % text) + try: + value = Decimal(_normalise_separators(s)) + except InvalidOperation: + raise ValueError("not an amount: %r" % text) from None + return -value if negative else value + + +def parse_date(text: str) -> dt.date: + """Parse ``YYYY-MM-DD``, ``DD.MM.YYYY`` or ``MM/DD/YYYY``.""" + s = text.strip() + for fmt in _DATE_FORMATS: + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError("unrecognised date: %r" % text) + + +def read_rows(text: str, delimiter: str = ",") -> List[StatementRow]: + """Read ``date, description, amount[, category]`` rows; the first line is the header.""" + reader = csv.reader(io.StringIO(text), delimiter=delimiter) + try: + header = [name.strip().lower() for name in next(reader)] + except StopIteration: + raise ImportFormatError(1, "empty file") from None + missing = [name for name in ("date", "description", "amount") if name not in header] + if missing: + raise ImportFormatError(1, "missing columns: %s" % ", ".join(missing)) + rows: List[StatementRow] = [] + for record in reader: + if not any(cell.strip() for cell in record): + continue + fields = dict(zip(header, record)) + try: + rows.append( + StatementRow( + line=reader.line_num, + date=parse_date(fields["date"]), + description=fields["description"].strip(), + amount=parse_amount(fields["amount"]), + category=fields.get("category", "").strip(), + ) + ) + except (KeyError, ValueError) as exc: + raise ImportFormatError(reader.line_num, str(exc)) from None + return rows + + +def to_transactions( + rows: List[StatementRow], + bank: str = "1000", + currency: str = "EUR", + income: str = "4900", + expense: str = "5900", +) -> List[Transaction]: + """Turn statement rows into transfers between ``bank`` and the row's category account.""" + transactions = [] + for number, row in enumerate(rows, start=1): + counter = row.category or (income if row.amount >= 0 else expense) + amount = Money(row.amount, currency).rounded() + transactions.append( + Transaction.transfer("imp-%04d" % number, row.date, row.description, bank, counter, amount) + ) + return transactions + + +def load_statement(text: str, delimiter: str = ",", **options: str) -> List[Transaction]: + """Parse CSV text straight into transactions; keyword options go to :func:`to_transactions`.""" + return to_transactions(read_rows(text, delimiter), **options) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/money.py b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/money.py new file mode 100644 index 00000000..23d2682a --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/money.py @@ -0,0 +1,137 @@ +"""Immutable money amounts.""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal +from typing import List, Sequence, Union + +from .rounding import round_decimal + +_MINOR_UNITS = {"JPY": 0, "KRW": 0, "KWD": 3, "BHD": 3} + +Amount = Union[int, str, Decimal] + + +def minor_units(currency: str) -> int: + """Number of decimal places of the smallest unit of ``currency``.""" + return _MINOR_UNITS.get(currency.upper(), 2) + + +class CurrencyMismatch(ValueError): + """Raised when amounts in different currencies are combined.""" + + +@dataclass(frozen=True) +class Money: + amount: Decimal + currency: str = "EUR" + + def __post_init__(self) -> None: + if isinstance(self.amount, float): + raise TypeError("use str, int or Decimal for amounts, not float") + object.__setattr__(self, "amount", Decimal(self.amount)) + object.__setattr__(self, "currency", self.currency.upper()) + + @classmethod + def zero(cls, currency: str = "EUR") -> "Money": + return cls(Decimal(0), currency) + + @classmethod + def from_minor(cls, units: int, currency: str = "EUR") -> "Money": + return cls(Decimal(units).scaleb(-minor_units(currency)), currency) + + def to_minor(self) -> int: + """The amount as an integer number of minor units (cents).""" + scaled = self.amount.scaleb(minor_units(self.currency)) + if scaled != scaled.to_integral_value(): + raise ValueError("amount %s has sub-unit precision" % self.amount) + return int(scaled) + + def rounded(self, mode: str = "half_even") -> "Money": + places = minor_units(self.currency) + return Money(round_decimal(self.amount, places, mode), self.currency) + + def is_zero(self) -> bool: + return self.amount == 0 + + def _same_currency(self, other: "Money") -> None: + if not isinstance(other, Money): + raise TypeError("expected Money, got %s" % type(other).__name__) + if other.currency != self.currency: + raise CurrencyMismatch("%s and %s cannot be combined" % (self.currency, other.currency)) + + def __add__(self, other: "Money") -> "Money": + self._same_currency(other) + return Money(self.amount + other.amount, self.currency) + + def __sub__(self, other: "Money") -> "Money": + self._same_currency(other) + return Money(self.amount - other.amount, self.currency) + + def __neg__(self) -> "Money": + return Money(-self.amount, self.currency) + + def __abs__(self) -> "Money": + return Money(abs(self.amount), self.currency) + + def __mul__(self, factor: Amount) -> "Money": + if isinstance(factor, float): + raise TypeError("use str, int or Decimal for factors, not float") + return Money(self.amount * Decimal(factor), self.currency).rounded() + + __rmul__ = __mul__ + + def __truediv__(self, divisor: Amount) -> "Money": + if isinstance(divisor, float): + raise TypeError("use str, int or Decimal for divisors, not float") + return Money(self.amount / Decimal(divisor), self.currency).rounded() + + def __lt__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount < other.amount + + def __le__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount <= other.amount + + def __gt__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount > other.amount + + def __ge__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount >= other.amount + + def allocate(self, ratios: Sequence[int]) -> List["Money"]: + """Split into ``len(ratios)`` parts proportional to ``ratios``. + + Every part is a whole number of minor units and the parts always add up + to the original amount. Leftover minor units go one each to the first + parts with a non-zero ratio; negative amounts are split like positive + ones with the sign applied afterwards. + """ + if not ratios or any(r < 0 for r in ratios): + raise ValueError("ratios must be non-empty and non-negative") + total = sum(ratios) + if total == 0: + raise ValueError("ratios must not all be zero") + minor = self.to_minor() + sign = -1 if minor < 0 else 1 + magnitude = abs(minor) + shares = [magnitude * r // total for r in ratios] + remainder = magnitude - sum(shares) + recipients = [i for i, r in enumerate(ratios) if r > 0] + for i in recipients[:remainder]: + shares[i] += 1 + return [Money.from_minor(sign * share, self.currency) for share in shares] + + def split(self, parts: int) -> List["Money"]: + """Split into ``parts`` nearly equal parts that add up exactly.""" + if parts < 1: + raise ValueError("parts must be positive") + return self.allocate([1] * parts) + + def __str__(self) -> str: + shown = self.rounded() + return "%s %s" % (format(shown.amount, "f"), self.currency) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/reports.py b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/reports.py new file mode 100644 index 00000000..e5391366 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/reports.py @@ -0,0 +1,111 @@ +"""Reports built on top of the journal.""" + +from __future__ import annotations + +import datetime as dt +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple + +from .accounts import AccountKind +from .journal import Journal +from .money import Money +from .utils import first_of_month, group_by + + +@dataclass(frozen=True) +class IncomeStatement: + income: Money + expenses: Money + by_account: Dict[str, Money] + + @property + def net(self) -> Money: + return self.income - self.expenses + + +def monthly_totals( + journal: Journal, + code: str, + start: Optional[dt.date] = None, + end: Optional[dt.date] = None, + currency: Optional[str] = None, +) -> Dict[dt.date, Money]: + """Net movement of an account per calendar month, keyed by the first day of the month, oldest first.""" + currency = currency or journal.base_currency + transactions = journal.transactions(start, end, code) + groups = group_by(transactions, lambda tx: (tx.date.year, tx.date.month)) + totals: Dict[dt.date, Money] = {} + for items in groups.values(): + month = first_of_month(items[0].date) + total = Money.zero(currency) + for tx in items: + total = total + tx.amount_for(code, currency) + totals[month] = total + return totals + + +def income_statement( + journal: Journal, + start: dt.date, + end: dt.date, + currency: Optional[str] = None, +) -> IncomeStatement: + """Income and expenses in ``[start, end]``; both totals are positive numbers.""" + currency = currency or journal.base_currency + income = Money.zero(currency) + expenses = Money.zero(currency) + by_account: Dict[str, Money] = {} + for account in journal.chart: + if account.kind not in (AccountKind.INCOME, AccountKind.EXPENSE): + continue + moved = journal.movement(account.code, start, end, currency) + if moved.is_zero(): + continue + if account.kind is AccountKind.INCOME: + by_account[account.code] = -moved + income = income - moved + else: + by_account[account.code] = moved + expenses = expenses + moved + return IncomeStatement(income, expenses, by_account) + + +def balance_sheet(journal: Journal, as_of: dt.date, currency: Optional[str] = None) -> Dict[str, Money]: + """Assets, liabilities and equity (including earnings not yet closed to equity).""" + totals = journal.kind_totals(as_of, currency) + assets = totals[AccountKind.ASSET] + liabilities = -totals[AccountKind.LIABILITY] + equity = -(totals[AccountKind.EQUITY] + totals[AccountKind.INCOME] + totals[AccountKind.EXPENSE]) + return {"assets": assets, "liabilities": liabilities, "equity": equity} + + +def trial_balance_rows( + journal: Journal, + as_of: Optional[dt.date] = None, + currency: Optional[str] = None, +) -> List[Tuple[str, str, Money, Money]]: + """Rows of ``(code, name, debit, credit)`` for every account with a balance.""" + currency = currency or journal.base_currency + rows = [] + for code, value in journal.trial_balance(as_of, currency).items(): + name = journal.chart.get(code).name + zero = Money.zero(currency) + if value.amount > 0: + rows.append((code, name, value, zero)) + else: + rows.append((code, name, zero, -value)) + return rows + + +def top_expenses( + journal: Journal, + start: dt.date, + end: dt.date, + limit: int = 3, +) -> List[Tuple[str, Money]]: + """The biggest expense accounts in the period, largest first (ties by account code).""" + statement = income_statement(journal, start, end) + expense_codes = [a.code for a in journal.chart.by_kind(AccountKind.EXPENSE)] + ranked = [(code, statement.by_account[code]) for code in expense_codes if code in statement.by_account] + ranked.sort(key=lambda item: (-item[1].amount, item[0])) + return ranked[:limit] diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/rounding.py b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/rounding.py new file mode 100644 index 00000000..1e6e431d --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/rounding.py @@ -0,0 +1,48 @@ +"""Decimal rounding helpers.""" + +from __future__ import annotations + +from decimal import ( + ROUND_CEILING, + ROUND_DOWN, + ROUND_FLOOR, + ROUND_HALF_EVEN, + ROUND_HALF_UP, + ROUND_UP, + Decimal, +) + +_MODES = { + "half_up": ROUND_HALF_UP, + "down": ROUND_DOWN, + "up": ROUND_UP, + "floor": ROUND_FLOOR, + "ceiling": ROUND_CEILING, +} + + +def quantum(places: int) -> Decimal: + """The Decimal with ``places`` decimal places, e.g. ``quantum(2) == Decimal('0.01')``.""" + return Decimal(1).scaleb(-places) + + +def round_half_even(value: Decimal, places: int = 2) -> Decimal: + """Banker's rounding: ties go to the neighbour whose last digit is even.""" + return value.quantize(quantum(places), rounding=ROUND_HALF_EVEN) + + +def round_decimal(value: Decimal, places: int = 2, mode: str = "half_even") -> Decimal: + """Round ``value`` to ``places`` decimal places using a named rounding mode.""" + if mode == "half_even": + return round_half_even(value, places) + if mode not in _MODES: + raise ValueError("unknown rounding mode: %s" % mode) + return value.quantize(quantum(places), rounding=_MODES[mode]) + + +def round_to_increment(value: Decimal, increment: Decimal, mode: str = "half_even") -> Decimal: + """Round to a multiple of ``increment`` (for example 0.05 for cash rounding).""" + if increment <= 0: + raise ValueError("increment must be positive") + steps = round_decimal(value / increment, 0, mode) + return steps * increment diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/__init__.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/__init__.py new file mode 100644 index 00000000..d2fecc56 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/__init__.py @@ -0,0 +1,17 @@ +"""ledger: a small double-entry bookkeeping library.""" + +from .accounts import Account, AccountKind, Chart, default_chart +from .journal import Journal +from .money import Money +from .transactions import Posting, Transaction + +__all__ = [ + "Account", + "AccountKind", + "Chart", + "Journal", + "Money", + "Posting", + "Transaction", + "default_chart", +] diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/accounts.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/accounts.py new file mode 100644 index 00000000..5924e0d8 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/accounts.py @@ -0,0 +1,102 @@ +"""Accounts and the chart of accounts.""" + +from __future__ import annotations + +from enum import Enum +from typing import Dict, Iterable, Iterator, List, Optional + + +class AccountKind(Enum): + ASSET = "asset" + LIABILITY = "liability" + EQUITY = "equity" + INCOME = "income" + EXPENSE = "expense" + + @property + def normal_side(self) -> str: + """The side on which the account normally grows.""" + if self in (AccountKind.ASSET, AccountKind.EXPENSE): + return "debit" + return "credit" + + +class UnknownAccount(KeyError): + """Raised when an account code is not in the chart.""" + + +class DuplicateAccount(ValueError): + """Raised when an account code is added twice.""" + + +class Account: + def __init__(self, code: str, name: str, kind: AccountKind, labels: List[str] = []) -> None: + self.code = code + self.name = name + self.kind = kind + self.labels = labels + + def add_label(self, label: str) -> None: + if label not in self.labels: + self.labels.append(label) + + def has_label(self, label: str) -> bool: + return label in self.labels + + def __repr__(self) -> str: + return "Account(%r, %r, %s)" % (self.code, self.name, self.kind.name) + + +class Chart: + """A chart of accounts, indexed by account code.""" + + def __init__(self, accounts: Iterable[Account] = ()) -> None: + self._accounts: Dict[str, Account] = {} + for account in accounts: + self.add(account) + + def add(self, account: Account) -> Account: + if account.code in self._accounts: + raise DuplicateAccount(account.code) + self._accounts[account.code] = account + return account + + def get(self, code: str) -> Account: + try: + return self._accounts[code] + except KeyError: + raise UnknownAccount(code) from None + + def __contains__(self, code: object) -> bool: + return code in self._accounts + + def __len__(self) -> int: + return len(self._accounts) + + def __iter__(self) -> Iterator[Account]: + for code in sorted(self._accounts): + yield self._accounts[code] + + def by_kind(self, kind: AccountKind) -> List[Account]: + return [a for a in self if a.kind is kind] + + def by_label(self, label: str) -> List[Account]: + return [a for a in self if a.has_label(label)] + + +def default_chart() -> Chart: + """The chart used by the command line tool.""" + rows = [ + ("1000", "Bank", AccountKind.ASSET), + ("1100", "Receivables", AccountKind.ASSET), + ("2000", "Payables", AccountKind.LIABILITY), + ("3000", "Owner equity", AccountKind.EQUITY), + ("4000", "Sales", AccountKind.INCOME), + ("4100", "Interest income", AccountKind.INCOME), + ("4900", "Other income", AccountKind.INCOME), + ("5000", "Rent", AccountKind.EXPENSE), + ("5100", "Groceries", AccountKind.EXPENSE), + ("5200", "Utilities", AccountKind.EXPENSE), + ("5900", "Other expenses", AccountKind.EXPENSE), + ] + return Chart(Account(code, name, kind) for code, name, kind in rows) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/calendar.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/calendar.py new file mode 100644 index 00000000..448df7e0 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/calendar.py @@ -0,0 +1,78 @@ +"""Business-day arithmetic with a holiday list.""" + +from __future__ import annotations + +import datetime as dt +from typing import FrozenSet, Iterable, Set + + +def fixed_holidays(year: int) -> Set[dt.date]: + """Fixed-date public holidays: New Year, Labour Day, Christmas and Boxing Day.""" + return {dt.date(year, 1, 1), dt.date(year, 5, 1), dt.date(year, 12, 25), dt.date(year, 12, 26)} + + +class BusinessCalendar: + """Knows which days are business days: not a weekend day and not a holiday.""" + + def __init__(self, holidays: Iterable[dt.date] = (), weekend: Iterable[int] = (5, 6)) -> None: + self.holidays: FrozenSet[dt.date] = frozenset(holidays) + self.weekend: FrozenSet[int] = frozenset(weekend) + + @classmethod + def for_years(cls, years: Iterable[int]) -> "BusinessCalendar": + holidays: Set[dt.date] = set() + for year in years: + holidays |= fixed_holidays(year) + return cls(holidays) + + def is_business_day(self, d: dt.date) -> bool: + return d.weekday() not in self.weekend and d not in self.holidays + + def next_business_day(self, d: dt.date) -> dt.date: + """``d`` itself if it is a business day, otherwise the next one.""" + while not self.is_business_day(d): + d += dt.timedelta(days=1) + return d + + def previous_business_day(self, d: dt.date) -> dt.date: + """``d`` itself if it is a business day, otherwise the previous one.""" + while not self.is_business_day(d): + d -= dt.timedelta(days=1) + return d + + def add_business_days(self, d: dt.date, n: int) -> dt.date: + """Move ``n`` business days forward (backward for negative ``n``). + + Each step goes to the next business day strictly after (before) the + current date, so starting on a weekend or holiday is fine: Saturday + plus one business day is Monday. ``n == 0`` returns ``d`` unchanged. + """ + step = dt.timedelta(days=1 if n >= 0 else -1) + current = self.next_business_day(d) if n >= 0 else self.previous_business_day(d) + remaining = abs(n) + while remaining: + current += step + if self.is_business_day(current): + remaining -= 1 + return current + + def business_days_between(self, start: dt.date, end: dt.date) -> int: + """Number of business days after ``start`` up to and including ``end`` (negative if ``end`` is earlier).""" + if end < start: + return -self.business_days_between(end, start) + count = 0 + current = start + while current < end: + current += dt.timedelta(days=1) + if self.is_business_day(current): + count += 1 + return count + + def business_days_in_month(self, year: int, month: int) -> int: + count = 0 + current = dt.date(year, month, 1) + while current.month == month: + if self.is_business_day(current): + count += 1 + current += dt.timedelta(days=1) + return count diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/cli.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/cli.py new file mode 100644 index 00000000..29b4b2d0 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/cli.py @@ -0,0 +1,56 @@ +"""Command line interface: ``python3 -m ledger.cli COMMAND STATEMENT.csv``.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path +from typing import List, Optional, TextIO + +from .accounts import UnknownAccount, default_chart +from .exporter import format_amount, journal_to_json, transactions_to_csv, trial_balance_to_csv +from .importer import ImportFormatError, load_statement +from .journal import Journal +from .reports import monthly_totals + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="ledger", description="Inspect a bank statement as a double-entry ledger.") + parser.add_argument("command", choices=["balance", "monthly", "trial", "export", "json"]) + parser.add_argument("file", help="statement CSV with columns date, description, amount[, category]") + parser.add_argument("--bank", default="1000", help="account code of the bank account (default 1000)") + parser.add_argument("--account", help="account to report on (default: the bank account)") + parser.add_argument("--currency", default="EUR") + parser.add_argument("--delimiter", default=",") + parser.add_argument("--style", default="plain", choices=["plain", "parens", "german"]) + return parser + + +def main(argv: Optional[List[str]] = None, out: Optional[TextIO] = None) -> int: + out = out or sys.stdout + args = build_parser().parse_args(argv) + try: + text = Path(args.file).read_text(encoding="utf-8") + transactions = load_statement(text, args.delimiter, bank=args.bank, currency=args.currency) + journal = Journal(default_chart(), args.currency) + journal.post_all(transactions) + account = args.account or args.bank + if args.command == "balance": + print(format_amount(journal.balance(account), args.style), file=out) + elif args.command == "monthly": + for month, total in monthly_totals(journal, account).items(): + print("%s %s" % (month.strftime("%Y-%m"), format_amount(total, args.style)), file=out) + elif args.command == "trial": + out.write(trial_balance_to_csv(journal)) + elif args.command == "export": + out.write(transactions_to_csv(journal.transactions())) + else: + print(journal_to_json(journal), file=out) + except (OSError, ImportFormatError, UnknownAccount) as exc: + print("error: %s" % exc, file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/exporter.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/exporter.py new file mode 100644 index 00000000..67714a78 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/exporter.py @@ -0,0 +1,88 @@ +"""Export journal data as text.""" + +from __future__ import annotations + +import csv +import datetime as dt +import io +import json +from typing import Iterable, Optional + +from .journal import Journal +from .money import Money, minor_units +from .reports import trial_balance_rows +from .transactions import Transaction + +_SWAP_SEPARATORS = str.maketrans({",": ".", ".": ","}) + + +def format_amount(money: Money, style: str = "plain") -> str: + """Format an amount without currency code. + + ``plain`` gives ``-1234.50``, ``parens`` gives ``(1234.50)`` for negative + values and ``german`` gives ``-1.234,50``. + """ + places = minor_units(money.currency) + value = money.rounded().amount + if style == "plain": + return format(value, "f") + if style == "parens": + text = format(abs(value), "f") + return "(%s)" % text if value < 0 else text + if style == "german": + text = format(abs(value), ",.%df" % places).translate(_SWAP_SEPARATORS) + return "-" + text if value < 0 else text + raise ValueError("unknown style: %s" % style) + + +def transactions_to_csv(transactions: Iterable[Transaction]) -> str: + """One CSV row per posting: ``id,date,description,account,amount,currency``.""" + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(["id", "date", "description", "account", "amount", "currency"]) + for tx in transactions: + for posting in tx.postings: + writer.writerow([ + tx.id, + tx.date.isoformat(), + tx.description, + posting.account, + format_amount(posting.amount), + posting.amount.currency, + ]) + return buffer.getvalue() + + +def trial_balance_to_csv(journal: Journal, as_of: Optional[dt.date] = None) -> str: + """The trial balance as ``code,name,debit,credit`` rows.""" + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(["code", "name", "debit", "credit"]) + for code, name, debit, credit in trial_balance_rows(journal, as_of): + writer.writerow([code, name, format_amount(debit), format_amount(credit)]) + return buffer.getvalue() + + +def journal_to_json(journal: Journal) -> str: + """The whole journal as indented JSON with sorted keys.""" + payload = { + "base_currency": journal.base_currency, + "transactions": [ + { + "id": tx.id, + "date": tx.date.isoformat(), + "description": tx.description, + "tags": list(tx.tags), + "postings": [ + { + "account": p.account, + "amount": format_amount(p.amount), + "currency": p.amount.currency, + } + for p in tx.postings + ], + } + for tx in journal.transactions() + ], + } + return json.dumps(payload, indent=2, sort_keys=True) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/fx.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/fx.py new file mode 100644 index 00000000..cdb4c023 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/fx.py @@ -0,0 +1,60 @@ +"""Exchange rates and currency conversion.""" + +from __future__ import annotations + +import datetime as dt +from bisect import bisect_right +from decimal import Decimal +from typing import Dict, List, Tuple, Union + +from .money import Money, minor_units +from .rounding import round_decimal + + +class MissingRate(LookupError): + """Raised when no rate is known for a currency on a date.""" + + +class RateTable: + """Rates quoted against a base currency: units of currency per one unit of base.""" + + def __init__(self, base: str = "EUR") -> None: + self.base = base.upper() + self._rates: Dict[str, List[Tuple[dt.date, Decimal]]] = {} + + def set_rate(self, currency: str, rate: Union[str, int, Decimal], on: dt.date) -> None: + currency = currency.upper() + if currency == self.base: + raise ValueError("the base currency always has rate 1") + value = Decimal(rate) + if value <= 0: + raise ValueError("rate must be positive") + series = [entry for entry in self._rates.get(currency, []) if entry[0] != on] + series.append((on, value)) + series.sort() + self._rates[currency] = series + + def rate(self, currency: str, on: dt.date) -> Decimal: + """The most recent rate on or before ``on``.""" + currency = currency.upper() + if currency == self.base: + return Decimal(1) + series = self._rates.get(currency) + if not series: + raise MissingRate("no rate for %s" % currency) + index = bisect_right([entry[0] for entry in series], on) + if index == 0: + raise MissingRate("no %s rate on or before %s" % (currency, on.isoformat())) + return series[index - 1][1] + + def cross_rate(self, source: str, target: str, on: dt.date) -> Decimal: + return self.rate(target, on) / self.rate(source, on) + + def convert(self, money: Money, target: str, on: dt.date) -> Money: + """Convert via the base currency, rounding half-even to the target's minor unit.""" + target = target.upper() + if money.currency == target: + return money + in_base = money.amount / self.rate(money.currency, on) + converted = in_base * self.rate(target, on) + return Money(round_decimal(converted, minor_units(target)), target) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/importer.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/importer.py new file mode 100644 index 00000000..e16e44a8 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/importer.py @@ -0,0 +1,165 @@ +"""Import bank statements from CSV text.""" + +from __future__ import annotations + +import csv +import datetime as dt +import io +import re +from dataclasses import dataclass +from decimal import Decimal, InvalidOperation +from typing import List, Optional + +from .money import Money +from .transactions import Transaction + +_CURRENCY_MARKS = "\u20ac$\u00a3" +_NUMERIC = re.compile(r"[0-9.,]*[0-9][0-9.,]*") +_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%m/%d/%Y") + + +class ImportFormatError(ValueError): + """Raised for malformed statement files; ``line`` is the 1-based line number.""" + + def __init__(self, line: int, message: str) -> None: + super().__init__("line %d: %s" % (line, message)) + self.line = line + + +@dataclass(frozen=True) +class StatementRow: + line: int + date: dt.date + description: str + amount: Decimal + category: str + + +def _lone_mark(s: str, mark: str) -> Optional[str]: + """Decide what the only kind of separator in ``s`` means. + + Returns ``mark`` if it is a decimal mark and ``None`` if it only groups + thousands. A mark that repeats, or that is followed by exactly three digits + after a leading group of one to three digits ("1,234", "12.345"), groups + thousands; anything else ("12,5", "0.125", "1234.567") is a decimal mark. + """ + if s.count(mark) > 1: + return None + head, _, tail = s.partition(mark) + if len(tail) == 3 and 1 <= len(head) <= 3 and head != "0": + return None + return mark + + +def _normalise_separators(s: str) -> str: + """Rewrite ``s`` with no grouping separators and at most one ``.`` as decimal mark.""" + last_dot, last_comma = s.rfind("."), s.rfind(",") + if last_dot < 0 and last_comma < 0: + return s + if last_dot >= 0 and last_comma >= 0: + decimal_mark: Optional[str] = "." if last_dot > last_comma else "," + elif last_comma >= 0: + # a lone comma is the European decimal mark + decimal_mark = "," + else: + decimal_mark = _lone_mark(s, ".") + if decimal_mark is None: + return s.replace(".", "").replace(",", "") + head, _, tail = s.rpartition(decimal_mark) + return head.replace(".", "").replace(",", "") + "." + tail + + +def parse_amount(text: str) -> Decimal: + """Parse an amount as it appears in a bank statement. + + Handles a leading or trailing minus, accounting-style negatives in + parentheses ("(1,234.50)"), currency marks, spaces as thousands + separators, and both "1,234.50" and "1.234,50" notation. + """ + s = text.strip() + negative = False + if s.startswith("(") and s.endswith(")"): + negative = True + s = s[1:-1].strip() + for mark in _CURRENCY_MARKS: + s = s.replace(mark, "") + s = s.replace("\u00a0", "").replace(" ", "") + if s.endswith("-"): + negative = True + s = s[:-1] + elif s.startswith("-"): + negative = True + s = s[1:] + elif s.startswith("+"): + s = s[1:] + if not _NUMERIC.fullmatch(s): + raise ValueError("not an amount: %r" % text) + try: + value = Decimal(_normalise_separators(s)) + except InvalidOperation: + raise ValueError("not an amount: %r" % text) from None + return -value if negative else value + + +def parse_date(text: str) -> dt.date: + """Parse ``YYYY-MM-DD``, ``DD.MM.YYYY`` or ``MM/DD/YYYY``.""" + s = text.strip() + for fmt in _DATE_FORMATS: + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError("unrecognised date: %r" % text) + + +def read_rows(text: str, delimiter: str = ",") -> List[StatementRow]: + """Read ``date, description, amount[, category]`` rows; the first line is the header.""" + reader = csv.reader(io.StringIO(text), delimiter=delimiter) + try: + header = [name.strip().lower() for name in next(reader)] + except StopIteration: + raise ImportFormatError(1, "empty file") from None + missing = [name for name in ("date", "description", "amount") if name not in header] + if missing: + raise ImportFormatError(1, "missing columns: %s" % ", ".join(missing)) + rows: List[StatementRow] = [] + for record in reader: + if not any(cell.strip() for cell in record): + continue + fields = dict(zip(header, record)) + try: + rows.append( + StatementRow( + line=reader.line_num, + date=parse_date(fields["date"]), + description=fields["description"].strip(), + amount=parse_amount(fields["amount"]), + category=fields.get("category", "").strip(), + ) + ) + except (KeyError, ValueError) as exc: + raise ImportFormatError(reader.line_num, str(exc)) from None + return rows + + +def to_transactions( + rows: List[StatementRow], + bank: str = "1000", + currency: str = "EUR", + income: str = "4900", + expense: str = "5900", +) -> List[Transaction]: + """Turn statement rows into transfers between ``bank`` and the row's category account.""" + transactions = [] + for number, row in enumerate(rows, start=1): + counter = row.category or (income if row.amount >= 0 else expense) + amount = Money(row.amount, currency).rounded() + transactions.append( + Transaction.transfer("imp-%04d" % number, row.date, row.description, bank, counter, amount) + ) + return transactions + + +def load_statement(text: str, delimiter: str = ",", **options: str) -> List[Transaction]: + """Parse CSV text straight into transactions; keyword options go to :func:`to_transactions`.""" + return to_transactions(read_rows(text, delimiter), **options) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/journal.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/journal.py new file mode 100644 index 00000000..74f6cfa5 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/journal.py @@ -0,0 +1,116 @@ +"""The journal: an ordered collection of validated transactions.""" + +from __future__ import annotations + +import datetime as dt +from typing import Dict, Iterable, List, NamedTuple, Optional, Set + +from .accounts import AccountKind, Chart +from .money import Money +from .transactions import Transaction + + +class DuplicateTransaction(ValueError): + """Raised when a transaction id is posted twice.""" + + +class StatementLine(NamedTuple): + date: dt.date + tx_id: str + description: str + amount: Money + balance: Money + + +class Journal: + def __init__(self, chart: Chart, base_currency: str = "EUR") -> None: + self.chart = chart + self.base_currency = base_currency + self._transactions: List[Transaction] = [] + self._ids: Set[str] = set() + + def __len__(self) -> int: + return len(self._transactions) + + def post(self, tx: Transaction) -> None: + """Validate ``tx`` and add it to the journal.""" + tx.validate() + if tx.id in self._ids: + raise DuplicateTransaction(tx.id) + for code in tx.accounts(): + self.chart.get(code) + self._ids.add(tx.id) + self._transactions.append(tx) + + def post_all(self, transactions: Iterable[Transaction]) -> None: + for tx in transactions: + self.post(tx) + + def transactions( + self, + start: Optional[dt.date] = None, + end: Optional[dt.date] = None, + account: Optional[str] = None, + ) -> List[Transaction]: + """Transactions in ``[start, end]`` (inclusive) touching ``account``, ordered by date then id.""" + selected = [ + tx + for tx in self._transactions + if (start is None or tx.date >= start) + and (end is None or tx.date <= end) + and (account is None or account in tx.accounts()) + ] + return sorted(selected, key=lambda tx: (tx.date, tx.id)) + + def movement( + self, + code: str, + start: Optional[dt.date] = None, + end: Optional[dt.date] = None, + currency: Optional[str] = None, + ) -> Money: + """Net debit (positive) or credit (negative) posted to ``code`` in the period.""" + self.chart.get(code) + currency = currency or self.base_currency + total = Money.zero(currency) + for tx in self.transactions(start, end, code): + total = total + tx.amount_for(code, currency) + return total + + def balance(self, code: str, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Money: + """Balance of ``code`` including everything posted up to and on ``as_of``.""" + return self.movement(code, None, as_of, currency) + + def natural_balance(self, code: str, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Money: + """Balance with the sign of the account's normal side (income and liabilities are positive).""" + value = self.balance(code, as_of, currency) + if self.chart.get(code).kind.normal_side == "credit": + return -value + return value + + def trial_balance(self, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Dict[str, Money]: + """Non-zero balances by account code.""" + result: Dict[str, Money] = {} + for account in self.chart: + value = self.balance(account.code, as_of, currency) + if not value.is_zero(): + result[account.code] = value + return result + + def statement(self, code: str, currency: Optional[str] = None) -> List[StatementLine]: + """Every transaction touching ``code`` with a running balance.""" + currency = currency or self.base_currency + running = Money.zero(currency) + lines: List[StatementLine] = [] + for tx in self.transactions(account=code): + amount = tx.amount_for(code, currency) + running = running + amount + lines.append(StatementLine(tx.date, tx.id, tx.description, amount, running)) + return lines + + def kind_totals(self, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Dict[AccountKind, Money]: + """Sum of balances per account kind.""" + totals = {kind: Money.zero(currency or self.base_currency) for kind in AccountKind} + for account in self.chart: + totals[account.kind] = totals[account.kind] + self.balance(account.code, as_of, currency) + return totals diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/money.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/money.py new file mode 100644 index 00000000..3067fd20 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/money.py @@ -0,0 +1,137 @@ +"""Immutable money amounts.""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal +from typing import List, Sequence, Union + +from .rounding import round_decimal + +_MINOR_UNITS = {"JPY": 0, "KRW": 0, "KWD": 3, "BHD": 3} + +Amount = Union[int, str, Decimal] + + +def minor_units(currency: str) -> int: + """Number of decimal places of the smallest unit of ``currency``.""" + return _MINOR_UNITS.get(currency.upper(), 2) + + +class CurrencyMismatch(ValueError): + """Raised when amounts in different currencies are combined.""" + + +@dataclass(frozen=True) +class Money: + amount: Decimal + currency: str = "EUR" + + def __post_init__(self) -> None: + if isinstance(self.amount, float): + raise TypeError("use str, int or Decimal for amounts, not float") + object.__setattr__(self, "amount", Decimal(self.amount)) + object.__setattr__(self, "currency", self.currency.upper()) + + @classmethod + def zero(cls, currency: str = "EUR") -> "Money": + return cls(Decimal(0), currency) + + @classmethod + def from_minor(cls, units: int, currency: str = "EUR") -> "Money": + return cls(Decimal(units).scaleb(-minor_units(currency)), currency) + + def to_minor(self) -> int: + """The amount as an integer number of minor units (cents).""" + scaled = self.amount.scaleb(minor_units(self.currency)) + if scaled != scaled.to_integral_value(): + raise ValueError("amount %s has sub-unit precision" % self.amount) + return int(scaled) + + def rounded(self, mode: str = "half_even") -> "Money": + places = minor_units(self.currency) + return Money(round_decimal(self.amount, places, mode), self.currency) + + def is_zero(self) -> bool: + return self.amount == 0 + + def _same_currency(self, other: "Money") -> None: + if not isinstance(other, Money): + raise TypeError("expected Money, got %s" % type(other).__name__) + if other.currency != self.currency: + raise CurrencyMismatch("%s and %s cannot be combined" % (self.currency, other.currency)) + + def __add__(self, other: "Money") -> "Money": + self._same_currency(other) + return Money(self.amount + other.amount, self.currency) + + def __sub__(self, other: "Money") -> "Money": + self._same_currency(other) + return Money(self.amount - other.amount, self.currency) + + def __neg__(self) -> "Money": + return Money(-self.amount, self.currency) + + def __abs__(self) -> "Money": + return Money(abs(self.amount), self.currency) + + def __mul__(self, factor: Amount) -> "Money": + if isinstance(factor, float): + raise TypeError("use str, int or Decimal for factors, not float") + return Money(self.amount * Decimal(factor), self.currency).rounded() + + __rmul__ = __mul__ + + def __truediv__(self, divisor: Amount) -> "Money": + if isinstance(divisor, float): + raise TypeError("use str, int or Decimal for divisors, not float") + return Money(self.amount / Decimal(divisor), self.currency).rounded() + + def __lt__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount < other.amount + + def __le__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount <= other.amount + + def __gt__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount > other.amount + + def __ge__(self, other: "Money") -> bool: + self._same_currency(other) + return self.amount >= other.amount + + def allocate(self, ratios: Sequence[int]) -> List["Money"]: + """Split into ``len(ratios)`` parts proportional to ``ratios``. + + Every part is a whole number of minor units and the parts always add up + to the original amount. Leftover minor units go one each to the first + parts with a non-zero ratio; negative amounts are split like positive + ones with the sign applied afterwards. + """ + if not ratios or any(r < 0 for r in ratios): + raise ValueError("ratios must be non-empty and non-negative") + total = sum(ratios) + if total == 0: + raise ValueError("ratios must not all be zero") + minor = self.to_minor() + sign = -1 if minor < 0 else 1 + magnitude = abs(minor) + shares = [magnitude * r // total for r in ratios] + remainder = minor - sum(shares) + recipients = [i for i, r in enumerate(ratios) if r > 0] + for i in recipients[:remainder]: + shares[i] += 1 + return [Money.from_minor(sign * share, self.currency) for share in shares] + + def split(self, parts: int) -> List["Money"]: + """Split into ``parts`` nearly equal parts that add up exactly.""" + if parts < 1: + raise ValueError("parts must be positive") + return self.allocate([1] * parts) + + def __str__(self) -> str: + shown = self.rounded() + return "%s %s" % (format(shown.amount, "f"), self.currency) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/reports.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/reports.py new file mode 100644 index 00000000..86ff11b1 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/reports.py @@ -0,0 +1,111 @@ +"""Reports built on top of the journal.""" + +from __future__ import annotations + +import datetime as dt +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple + +from .accounts import AccountKind +from .journal import Journal +from .money import Money +from .utils import first_of_month, group_by + + +@dataclass(frozen=True) +class IncomeStatement: + income: Money + expenses: Money + by_account: Dict[str, Money] + + @property + def net(self) -> Money: + return self.income - self.expenses + + +def monthly_totals( + journal: Journal, + code: str, + start: Optional[dt.date] = None, + end: Optional[dt.date] = None, + currency: Optional[str] = None, +) -> Dict[dt.date, Money]: + """Net movement of an account per calendar month, keyed by the first day of the month, oldest first.""" + currency = currency or journal.base_currency + transactions = journal.transactions(start, end, code) + groups = group_by(transactions, lambda tx: tx.date.month) + totals: Dict[dt.date, Money] = {} + for items in groups.values(): + month = first_of_month(items[0].date) + total = Money.zero(currency) + for tx in items: + total = total + tx.amount_for(code, currency) + totals[month] = total + return totals + + +def income_statement( + journal: Journal, + start: dt.date, + end: dt.date, + currency: Optional[str] = None, +) -> IncomeStatement: + """Income and expenses in ``[start, end]``; both totals are positive numbers.""" + currency = currency or journal.base_currency + income = Money.zero(currency) + expenses = Money.zero(currency) + by_account: Dict[str, Money] = {} + for account in journal.chart: + if account.kind not in (AccountKind.INCOME, AccountKind.EXPENSE): + continue + moved = journal.movement(account.code, start, end, currency) + if moved.is_zero(): + continue + if account.kind is AccountKind.INCOME: + by_account[account.code] = -moved + income = income - moved + else: + by_account[account.code] = moved + expenses = expenses + moved + return IncomeStatement(income, expenses, by_account) + + +def balance_sheet(journal: Journal, as_of: dt.date, currency: Optional[str] = None) -> Dict[str, Money]: + """Assets, liabilities and equity (including earnings not yet closed to equity).""" + totals = journal.kind_totals(as_of, currency) + assets = totals[AccountKind.ASSET] + liabilities = -totals[AccountKind.LIABILITY] + equity = -(totals[AccountKind.EQUITY] + totals[AccountKind.INCOME] + totals[AccountKind.EXPENSE]) + return {"assets": assets, "liabilities": liabilities, "equity": equity} + + +def trial_balance_rows( + journal: Journal, + as_of: Optional[dt.date] = None, + currency: Optional[str] = None, +) -> List[Tuple[str, str, Money, Money]]: + """Rows of ``(code, name, debit, credit)`` for every account with a balance.""" + currency = currency or journal.base_currency + rows = [] + for code, value in journal.trial_balance(as_of, currency).items(): + name = journal.chart.get(code).name + zero = Money.zero(currency) + if value.amount > 0: + rows.append((code, name, value, zero)) + else: + rows.append((code, name, zero, -value)) + return rows + + +def top_expenses( + journal: Journal, + start: dt.date, + end: dt.date, + limit: int = 3, +) -> List[Tuple[str, Money]]: + """The biggest expense accounts in the period, largest first (ties by account code).""" + statement = income_statement(journal, start, end) + expense_codes = [a.code for a in journal.chart.by_kind(AccountKind.EXPENSE)] + ranked = [(code, statement.by_account[code]) for code in expense_codes if code in statement.by_account] + ranked.sort(key=lambda item: (-item[1].amount, item[0])) + return ranked[:limit] diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/rounding.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/rounding.py new file mode 100644 index 00000000..725d0174 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/rounding.py @@ -0,0 +1,48 @@ +"""Decimal rounding helpers.""" + +from __future__ import annotations + +from decimal import ( + ROUND_CEILING, + ROUND_DOWN, + ROUND_FLOOR, + ROUND_HALF_EVEN, + ROUND_HALF_UP, + ROUND_UP, + Decimal, +) + +_MODES = { + "half_up": ROUND_HALF_UP, + "down": ROUND_DOWN, + "up": ROUND_UP, + "floor": ROUND_FLOOR, + "ceiling": ROUND_CEILING, +} + + +def quantum(places: int) -> Decimal: + """The Decimal with ``places`` decimal places, e.g. ``quantum(2) == Decimal('0.01')``.""" + return Decimal(1).scaleb(-places) + + +def round_half_even(value: Decimal, places: int = 2) -> Decimal: + """Banker's rounding: ties go to the neighbour whose last digit is even.""" + return Decimal(str(round(float(value), places))).quantize(quantum(places)) + + +def round_decimal(value: Decimal, places: int = 2, mode: str = "half_even") -> Decimal: + """Round ``value`` to ``places`` decimal places using a named rounding mode.""" + if mode == "half_even": + return round_half_even(value, places) + if mode not in _MODES: + raise ValueError("unknown rounding mode: %s" % mode) + return value.quantize(quantum(places), rounding=_MODES[mode]) + + +def round_to_increment(value: Decimal, increment: Decimal, mode: str = "half_even") -> Decimal: + """Round to a multiple of ``increment`` (for example 0.05 for cash rounding).""" + if increment <= 0: + raise ValueError("increment must be positive") + steps = round_decimal(value / increment, 0, mode) + return steps * increment diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/transactions.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/transactions.py new file mode 100644 index 00000000..f0f27d06 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/transactions.py @@ -0,0 +1,116 @@ +"""Postings and balanced transactions.""" + +from __future__ import annotations + +import datetime as dt +from dataclasses import dataclass, field +from decimal import Decimal +from typing import Dict, Iterable, List, Mapping, Optional + +from .money import Money +from .utils import ensure_date, group_by + + +class UnbalancedTransaction(ValueError): + """Raised when the postings of a transaction do not add up to zero.""" + + +@dataclass(frozen=True) +class Posting: + """One line of a transaction. Positive amounts are debits, negative amounts credits.""" + + account: str + amount: Money + memo: str = "" + + +@dataclass +class Transaction: + id: str + date: dt.date + description: str + postings: List[Posting] + tags: List[str] = field(default_factory=list) + + def __post_init__(self) -> None: + self.date = ensure_date(self.date) + + @classmethod + def transfer( + cls, + id: str, + date: dt.date, + description: str, + debit: str, + credit: str, + amount: Money, + tags: Iterable[str] = (), + ) -> "Transaction": + """Move ``amount`` from the ``credit`` account to the ``debit`` account.""" + postings = [Posting(debit, amount), Posting(credit, -amount)] + return cls(id, date, description, postings, list(tags)) + + @classmethod + def from_split( + cls, + id: str, + date: dt.date, + description: str, + source: str, + targets: Mapping[str, int], + amount: Money, + ) -> "Transaction": + """Distribute ``amount`` from ``source`` over several accounts in proportion to ``targets``.""" + codes = list(targets) + shares = amount.allocate([targets[code] for code in codes]) + postings = [Posting(code, share) for code, share in zip(codes, shares)] + postings.append(Posting(source, -amount)) + return cls(id, date, description, postings) + + def imbalance(self) -> Dict[str, Decimal]: + """Non-zero sums of the postings, per currency.""" + sums: Dict[str, Decimal] = {} + for currency, items in group_by(self.postings, lambda p: p.amount.currency).items(): + total = sum((p.amount.amount for p in items), Decimal(0)) + if total != 0: + sums[currency] = total + return sums + + def is_balanced(self) -> bool: + return not self.imbalance() + + def validate(self) -> None: + if len(self.postings) < 2: + raise ValueError("transaction %s needs at least two postings" % self.id) + gap = self.imbalance() + if gap: + detail = ", ".join("%s %s" % (value, cur) for cur, value in sorted(gap.items())) + raise UnbalancedTransaction("transaction %s is off by %s" % (self.id, detail)) + + def accounts(self) -> List[str]: + """Distinct account codes in order of first appearance.""" + seen: List[str] = [] + for posting in self.postings: + if posting.account not in seen: + seen.append(posting.account) + return seen + + def amount_for(self, account: str, currency: Optional[str] = None) -> Money: + """Net amount posted to ``account`` (in ``currency``, default: the first posting's).""" + currency = currency or self.postings[0].amount.currency + total = Money.zero(currency) + for posting in self.postings: + if posting.account == account and posting.amount.currency == currency: + total = total + posting.amount + return total + + def reversed(self, new_id: str, on: Optional[dt.date] = None) -> "Transaction": + """The opposite transaction, used to cancel this one.""" + postings = [Posting(p.account, -p.amount, p.memo) for p in self.postings] + return Transaction( + new_id, + on or self.date, + "Reversal of %s" % self.description, + postings, + list(self.tags), + ) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/utils.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/utils.py new file mode 100644 index 00000000..174e73e4 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/utils.py @@ -0,0 +1,65 @@ +"""Small helpers shared by the ledger modules.""" + +from __future__ import annotations + +from datetime import date, timedelta +from typing import Callable, Dict, Hashable, Iterable, Iterator, List, Sequence, TypeVar, Union + +T = TypeVar("T") +K = TypeVar("K", bound=Hashable) + + +def chunked(items: Sequence[T], size: int) -> Iterator[Sequence[T]]: + """Yield consecutive slices of ``items`` with at most ``size`` elements.""" + if size < 1: + raise ValueError("size must be positive") + for start in range(0, len(items), size): + yield items[start:start + size] + + +def group_by(items: Iterable[T], key: Callable[[T], K]) -> Dict[K, List[T]]: + """Group items by ``key`` keeping first-seen order of keys and items.""" + groups: Dict[K, List[T]] = {} + for item in items: + groups.setdefault(key(item), []).append(item) + return groups + + +def ensure_date(value: Union[str, date]) -> date: + """Accept a ``date`` or an ISO ``YYYY-MM-DD`` string.""" + if isinstance(value, date): + return value + return date.fromisoformat(value) + + +def days_in_month(year: int, month: int) -> int: + start = date(year, month, 1) + following = date(year + (month == 12), month % 12 + 1, 1) + return (following - start).days + + +def first_of_month(d: date) -> date: + return d.replace(day=1) + + +def last_of_month(d: date) -> date: + return d.replace(day=days_in_month(d.year, d.month)) + + +def add_months(d: date, months: int) -> date: + """Shift ``d`` by whole months, clamping the day to the end of the target month.""" + year, month0 = divmod(d.year * 12 + d.month - 1 + months, 12) + month = month0 + 1 + return date(year, month, min(d.day, days_in_month(year, month))) + + +def daterange(start: date, end: date) -> Iterator[date]: + """Every date from ``start`` to ``end`` inclusive.""" + current = start + while current <= end: + yield current + current += timedelta(days=1) + + +def clamp(value, low, high): + return max(low, min(value, high)) diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/helpers.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/helpers.py new file mode 100644 index 00000000..5bad8eb9 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/helpers.py @@ -0,0 +1,36 @@ +"""Shared fixtures for the ledger tests.""" + +from datetime import date + +from ledger import Journal, Money, Transaction, default_chart + + +def eur(text): + return Money(text, "EUR") + + +def sample_journal(): + """Three months of activity in 2024; the bank balance ends at 5253.35.""" + journal = Journal(default_chart()) + journal.post_all([ + Transaction.transfer("t1", date(2024, 1, 5), "Opening deposit", "1000", "3000", eur("5000.00")), + Transaction.transfer("t2", date(2024, 1, 10), "Consulting invoice", "1000", "4000", eur("1200.00")), + Transaction.transfer("t3", date(2024, 1, 15), "January rent", "5000", "1000", eur("800.00")), + Transaction.transfer("t4", date(2024, 2, 3), "Groceries", "5100", "1000", eur("150.25")), + Transaction.transfer("t5", date(2024, 2, 20), "Consulting invoice", "1000", "4000", eur("900.00")), + Transaction.transfer("t6", date(2024, 2, 28), "Electricity", "5200", "1000", eur("96.40")), + Transaction.transfer("t7", date(2024, 3, 1), "March rent", "5000", "1000", eur("800.00")), + ]) + return journal + + +def two_year_journal(): + """Activity in January 2023 and January 2024 plus December 2023.""" + journal = Journal(default_chart()) + journal.post_all([ + Transaction.transfer("a1", date(2023, 1, 9), "Salary", "1000", "4000", eur("2000.00")), + Transaction.transfer("a2", date(2023, 12, 20), "Salary", "1000", "4000", eur("2100.00")), + Transaction.transfer("a3", date(2024, 1, 8), "Salary", "1000", "4000", eur("2200.00")), + Transaction.transfer("a4", date(2024, 1, 20), "Rent", "5000", "1000", eur("700.00")), + ]) + return journal diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_accounts.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_accounts.py new file mode 100644 index 00000000..178c0610 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_accounts.py @@ -0,0 +1,69 @@ +import unittest + +from ledger.accounts import Account, AccountKind, Chart, DuplicateAccount, UnknownAccount, default_chart + + +class AccountKindTests(unittest.TestCase): + def test_normal_sides(self): + self.assertEqual(AccountKind.ASSET.normal_side, "debit") + self.assertEqual(AccountKind.EXPENSE.normal_side, "debit") + self.assertEqual(AccountKind.LIABILITY.normal_side, "credit") + self.assertEqual(AccountKind.EQUITY.normal_side, "credit") + self.assertEqual(AccountKind.INCOME.normal_side, "credit") + + +class AccountTests(unittest.TestCase): + def test_labels_from_iterable(self): + account = Account("1000", "Bank", AccountKind.ASSET, ["cash", "main"]) + self.assertEqual(account.labels, ["cash", "main"]) + self.assertTrue(account.has_label("main")) + + def test_add_label_ignores_duplicates(self): + account = Account("1000", "Bank", AccountKind.ASSET) + account.add_label("cash") + account.add_label("cash") + self.assertEqual(account.labels, ["cash"]) + self.assertTrue(account.has_label("cash")) + + def test_labels_belong_to_one_account(self): + first = Account("1000", "Bank", AccountKind.ASSET) + second = Account("1100", "Receivables", AccountKind.ASSET) + first.add_label("liquid") + self.assertEqual(second.labels, []) + self.assertFalse(second.has_label("liquid")) + + +class ChartTests(unittest.TestCase): + def setUp(self): + self.chart = Chart([ + Account("2000", "Payables", AccountKind.LIABILITY), + Account("1000", "Bank", AccountKind.ASSET), + Account("1100", "Receivables", AccountKind.ASSET), + ]) + + def test_iteration_is_sorted_by_code(self): + self.assertEqual([a.code for a in self.chart], ["1000", "1100", "2000"]) + + def test_get_unknown_and_duplicate(self): + self.assertEqual(self.chart.get("1000").name, "Bank") + with self.assertRaises(UnknownAccount): + self.chart.get("9999") + with self.assertRaises(DuplicateAccount): + self.chart.add(Account("1000", "Other", AccountKind.ASSET)) + + def test_by_kind(self): + self.assertEqual([a.code for a in self.chart.by_kind(AccountKind.ASSET)], ["1000", "1100"]) + + def test_by_label_only_returns_labelled_accounts(self): + self.chart.get("1100").add_label("trade") + self.assertEqual([a.code for a in self.chart.by_label("trade")], ["1100"]) + + def test_default_chart(self): + chart = default_chart() + self.assertIn("1000", chart) + self.assertEqual(len(chart), 11) + self.assertEqual(chart.get("5000").kind, AccountKind.EXPENSE) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_calendar.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_calendar.py new file mode 100644 index 00000000..e9ce9a1c --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_calendar.py @@ -0,0 +1,67 @@ +import unittest +from datetime import date + +from ledger.calendar import BusinessCalendar, fixed_holidays + +# 2024-03-01 is a Friday, 2024-05-01 (Labour Day) a Wednesday, 2024-12-25 a Wednesday. + + +class CalendarTests(unittest.TestCase): + def setUp(self): + self.cal = BusinessCalendar.for_years([2024]) + + def test_fixed_holidays(self): + self.assertEqual( + sorted(fixed_holidays(2024)), + [date(2024, 1, 1), date(2024, 5, 1), date(2024, 12, 25), date(2024, 12, 26)], + ) + + def test_is_business_day(self): + self.assertTrue(self.cal.is_business_day(date(2024, 3, 1))) + self.assertFalse(self.cal.is_business_day(date(2024, 3, 2))) + self.assertFalse(self.cal.is_business_day(date(2024, 3, 3))) + self.assertFalse(self.cal.is_business_day(date(2024, 5, 1))) + + def test_custom_weekend(self): + cal = BusinessCalendar(weekend=(4, 5)) + self.assertFalse(cal.is_business_day(date(2024, 3, 1))) + self.assertTrue(cal.is_business_day(date(2024, 3, 3))) + + def test_next_and_previous_business_day(self): + self.assertEqual(self.cal.next_business_day(date(2024, 3, 1)), date(2024, 3, 1)) + self.assertEqual(self.cal.next_business_day(date(2024, 3, 2)), date(2024, 3, 4)) + self.assertEqual(self.cal.next_business_day(date(2024, 12, 25)), date(2024, 12, 27)) + self.assertEqual(self.cal.previous_business_day(date(2024, 3, 3)), date(2024, 3, 1)) + + def test_add_business_days_from_a_business_day(self): + self.assertEqual(self.cal.add_business_days(date(2024, 3, 1), 1), date(2024, 3, 4)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 4), 5), date(2024, 3, 11)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 4), -1), date(2024, 3, 1)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 4), 0), date(2024, 3, 4)) + + def test_add_business_days_skips_holidays(self): + self.assertEqual(self.cal.add_business_days(date(2024, 4, 30), 1), date(2024, 5, 2)) + self.assertEqual(self.cal.add_business_days(date(2024, 12, 24), 2), date(2024, 12, 30)) + + def test_add_business_days_from_a_saturday(self): + self.assertEqual(self.cal.add_business_days(date(2024, 3, 2), 1), date(2024, 3, 4)) + self.assertEqual(self.cal.add_business_days(date(2024, 3, 2), 3), date(2024, 3, 6)) + + def test_add_business_days_from_a_holiday(self): + self.assertEqual(self.cal.add_business_days(date(2024, 5, 1), 1), date(2024, 5, 2)) + + def test_business_days_between(self): + self.assertEqual(self.cal.business_days_between(date(2024, 3, 1), date(2024, 3, 4)), 1) + self.assertEqual(self.cal.business_days_between(date(2024, 3, 4), date(2024, 3, 8)), 4) + self.assertEqual(self.cal.business_days_between(date(2024, 3, 4), date(2024, 3, 4)), 0) + self.assertEqual(self.cal.business_days_between(date(2024, 3, 8), date(2024, 3, 4)), -4) + self.assertEqual(self.cal.business_days_between(date(2024, 4, 30), date(2024, 5, 3)), 2) + + def test_business_days_in_month(self): + self.assertEqual(self.cal.business_days_in_month(2024, 3), 21) + self.assertEqual(self.cal.business_days_in_month(2024, 5), 22) + self.assertEqual(self.cal.business_days_in_month(2024, 12), 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_cli.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_cli.py new file mode 100644 index 00000000..1e3d820e --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_cli.py @@ -0,0 +1,66 @@ +import contextlib +import io +import os +import tempfile +import unittest + +from ledger import cli + +SINGLE_YEAR = """date,description,amount,category +2024-01-05,Opening deposit,5000.00,3000 +2024-01-10,Consulting invoice,1200.00,4000 +2024-02-03,Groceries,-150.25,5100 +2024-02-20,Consulting invoice,900.00,4000 +""" + +TWO_YEARS = """date,description,amount,category +2023-01-09,Salary,2000.00,4000 +2023-12-20,Salary,2100.00,4000 +2024-01-08,Salary,2200.00,4000 +2024-01-20,Rent,-700.00,5000 +""" + + +class CliTests(unittest.TestCase): + def run_cli(self, content, *args): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "statement.csv") + with open(path, "w", encoding="utf-8") as handle: + handle.write(content) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(err): + code = cli.main([args[0], path, *args[1:]], out=out) + return code, out.getvalue(), err.getvalue() + + def test_balance(self): + code, out, _ = self.run_cli(SINGLE_YEAR, "balance") + self.assertEqual((code, out), (0, "6949.75\n")) + + def test_balance_styles(self): + _, out, _ = self.run_cli(SINGLE_YEAR, "balance", "--style", "german") + self.assertEqual(out, "6.949,75\n") + + def test_monthly_within_one_year(self): + code, out, _ = self.run_cli(SINGLE_YEAR, "monthly") + self.assertEqual((code, out), (0, "2024-01 6200.00\n2024-02 749.75\n")) + + def test_monthly_across_years(self): + _, out, _ = self.run_cli(TWO_YEARS, "monthly") + self.assertEqual(out.splitlines(), ["2023-01 2000.00", "2023-12 2100.00", "2024-01 1500.00"]) + + def test_trial_and_export(self): + _, trial, _ = self.run_cli(SINGLE_YEAR, "trial") + self.assertIn("1000,Bank,6949.75,0.00", trial.splitlines()) + _, export, _ = self.run_cli(SINGLE_YEAR, "export") + self.assertEqual(len(export.splitlines()), 1 + 2 * 4) + + def test_errors_return_two(self): + code, _, err = self.run_cli("date,amount\n", "balance") + self.assertEqual(code, 2) + self.assertIn("missing columns", err) + code, _, err = self.run_cli(SINGLE_YEAR.replace("5100", "9999"), "balance") + self.assertEqual(code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_exporter.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_exporter.py new file mode 100644 index 00000000..5478ee92 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_exporter.py @@ -0,0 +1,53 @@ +import json +import unittest +from datetime import date + +from helpers import eur, sample_journal +from ledger import Money, Transaction +from ledger.exporter import format_amount, journal_to_json, transactions_to_csv, trial_balance_to_csv + + +class FormatAmountTests(unittest.TestCase): + def test_styles(self): + value = Money("-1234.5") + self.assertEqual(format_amount(value), "-1234.50") + self.assertEqual(format_amount(value, "parens"), "(1234.50)") + self.assertEqual(format_amount(value, "german"), "-1.234,50") + self.assertEqual(format_amount(Money("1234567.891"), "german"), "1.234.567,89") + self.assertEqual(format_amount(Money("5"), "parens"), "5.00") + + def test_currency_without_minor_units(self): + self.assertEqual(format_amount(Money("1234", "JPY"), "german"), "1.234") + + def test_unknown_style(self): + with self.assertRaises(ValueError): + format_amount(Money("1"), "roman") + + +class CsvTests(unittest.TestCase): + def test_transactions_to_csv(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "Rent, January", "5000", "1000", eur("800.00")) + self.assertEqual( + transactions_to_csv([tx]), + "id,date,description,account,amount,currency\n" + 't1,2024-01-05,"Rent, January",5000,800.00,EUR\n' + 't1,2024-01-05,"Rent, January",1000,-800.00,EUR\n', + ) + + def test_trial_balance_to_csv(self): + lines = trial_balance_to_csv(sample_journal(), date(2024, 1, 31)).splitlines() + self.assertEqual(lines[0], "code,name,debit,credit") + self.assertIn("1000,Bank,5400.00,0.00", lines) + self.assertIn("3000,Owner equity,0.00,5000.00", lines) + + +class JsonTests(unittest.TestCase): + def test_journal_to_json(self): + data = json.loads(journal_to_json(sample_journal())) + self.assertEqual(data["base_currency"], "EUR") + self.assertEqual(len(data["transactions"]), 7) + self.assertEqual(data["transactions"][2]["postings"][0], {"account": "5000", "amount": "800.00", "currency": "EUR"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_fx.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_fx.py new file mode 100644 index 00000000..12d2f233 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_fx.py @@ -0,0 +1,74 @@ +import unittest +from datetime import date +from decimal import Decimal + +from ledger.fx import MissingRate, RateTable +from ledger.money import Money + +DAY = date(2024, 3, 15) + + +class RateTests(unittest.TestCase): + def setUp(self): + self.table = RateTable("EUR") + self.table.set_rate("USD", "1.10", date(2024, 1, 1)) + self.table.set_rate("USD", "1.20", date(2024, 3, 1)) + self.table.set_rate("GBP", "0.85", date(2024, 1, 1)) + + def test_base_rate_is_one(self): + self.assertEqual(self.table.rate("EUR", DAY), Decimal(1)) + + def test_latest_rate_on_or_before_date(self): + self.assertEqual(self.table.rate("USD", date(2024, 2, 29)), Decimal("1.10")) + self.assertEqual(self.table.rate("USD", date(2024, 3, 1)), Decimal("1.20")) + self.assertEqual(self.table.rate("usd", DAY), Decimal("1.20")) + + def test_missing_rates(self): + with self.assertRaises(MissingRate): + self.table.rate("CHF", DAY) + with self.assertRaises(MissingRate): + self.table.rate("USD", date(2023, 12, 31)) + + def test_invalid_rates(self): + with self.assertRaises(ValueError): + self.table.set_rate("EUR", "1", DAY) + with self.assertRaises(ValueError): + self.table.set_rate("CHF", "0", DAY) + + def test_setting_a_rate_twice_replaces_it(self): + self.table.set_rate("USD", "1.25", date(2024, 3, 1)) + self.assertEqual(self.table.rate("USD", DAY), Decimal("1.25")) + + +class ConvertTests(unittest.TestCase): + def setUp(self): + self.table = RateTable("EUR") + self.table.set_rate("USD", "1.10", date(2024, 1, 1)) + self.table.set_rate("GBP", "0.80", date(2024, 1, 1)) + self.table.set_rate("JPY", "160.45", date(2024, 1, 1)) + + def test_from_base(self): + self.assertEqual(self.table.convert(Money("100.00", "EUR"), "USD", DAY), Money("110.00", "USD")) + + def test_to_base(self): + self.assertEqual(self.table.convert(Money("110.00", "USD"), "EUR", DAY), Money("100.00", "EUR")) + + def test_between_two_foreign_currencies(self): + self.assertEqual(self.table.convert(Money("55.00", "USD"), "GBP", DAY), Money("40.00", "GBP")) + self.assertEqual(self.table.cross_rate("USD", "GBP", DAY).quantize(Decimal("0.0001")), Decimal("0.7273")) + + def test_same_currency_is_unchanged(self): + money = Money("12.34", "USD") + self.assertIs(self.table.convert(money, "usd", DAY), money) + + def test_target_without_minor_units(self): + self.assertEqual(self.table.convert(Money("10.00", "EUR"), "JPY", DAY), Money("1604", "JPY")) + + def test_ties_round_half_even(self): + self.table.set_rate("CHF", "1.07", date(2024, 1, 1)) + self.assertEqual(self.table.convert(Money("2.50", "EUR"), "CHF", DAY), Money("2.68", "CHF")) + self.assertEqual(self.table.convert(Money("1.50", "EUR"), "CHF", DAY), Money("1.60", "CHF")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_importer.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_importer.py new file mode 100644 index 00000000..89fb8803 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_importer.py @@ -0,0 +1,129 @@ +import unittest +from datetime import date +from decimal import Decimal + +from ledger import importer +from ledger.importer import ImportFormatError, parse_amount, parse_date + +STATEMENT = """date,description,amount,category +2024-01-05,Opening deposit,"5,000.00",3000 +2024-01-10,Consulting invoice,1200.00,4000 + +2024-01-15,January rent,-800.00,5000 +2024-01-16,Coffee,-3.50, +""" + +GERMAN = """Date;Description;Amount +15.03.2024;Miete;-1.234,50 +16.03.2024;Gehalt;2.500,00 +""" + + +class ParseAmountTests(unittest.TestCase): + def test_plain_numbers(self): + self.assertEqual(parse_amount("12"), Decimal("12")) + self.assertEqual(parse_amount("12.50"), Decimal("12.50")) + self.assertEqual(parse_amount(" 7.05 "), Decimal("7.05")) + + def test_signs(self): + self.assertEqual(parse_amount("-12.50"), Decimal("-12.50")) + self.assertEqual(parse_amount("+12.50"), Decimal("12.50")) + self.assertEqual(parse_amount("12.50-"), Decimal("-12.50")) + + def test_parenthesised_negatives(self): + self.assertEqual(parse_amount("(1,234.50)"), Decimal("-1234.50")) + self.assertEqual(parse_amount("( 12.00 )"), Decimal("-12.00")) + self.assertEqual(parse_amount("($99.99)"), Decimal("-99.99")) + + def test_currency_marks_and_spaces(self): + self.assertEqual(parse_amount("$1,234.50"), Decimal("1234.50")) + self.assertEqual(parse_amount("\u20ac 12,50"), Decimal("12.50")) + self.assertEqual(parse_amount("1 234,50"), Decimal("1234.50")) + self.assertEqual(parse_amount("1\u00a0234,50"), Decimal("1234.50")) + + def test_both_separators(self): + self.assertEqual(parse_amount("1,234.50"), Decimal("1234.50")) + self.assertEqual(parse_amount("1.234,50"), Decimal("1234.50")) + self.assertEqual(parse_amount("1,234,567.89"), Decimal("1234567.89")) + self.assertEqual(parse_amount("1.234.567,89"), Decimal("1234567.89")) + + def test_decimal_comma(self): + self.assertEqual(parse_amount("12,5"), Decimal("12.5")) + self.assertEqual(parse_amount("0,75"), Decimal("0.75")) + self.assertEqual(parse_amount("-1234,5"), Decimal("-1234.5")) + + def test_dot_as_thousands_separator(self): + self.assertEqual(parse_amount("1.234"), Decimal("1234")) + self.assertEqual(parse_amount("1.234.567"), Decimal("1234567")) + self.assertEqual(parse_amount("0.125"), Decimal("0.125")) + + def test_comma_as_thousands_separator(self): + self.assertEqual(parse_amount("1,234"), Decimal("1234")) + self.assertEqual(parse_amount("(12,345)"), Decimal("-12345")) + + def test_rejects_garbage(self): + for text in ("", "abc", "1e5", "--5", "1.2x", "NaN", "(5"): + with self.assertRaises(ValueError, msg=text): + parse_amount(text) + + +class ParseDateTests(unittest.TestCase): + def test_formats(self): + self.assertEqual(parse_date("2024-03-15"), date(2024, 3, 15)) + self.assertEqual(parse_date("15.03.2024"), date(2024, 3, 15)) + self.assertEqual(parse_date("03/15/2024"), date(2024, 3, 15)) + + def test_unknown_format(self): + with self.assertRaises(ValueError): + parse_date("March 15th") + + +class ReadRowsTests(unittest.TestCase): + def test_reads_rows_and_skips_blank_lines(self): + rows = importer.read_rows(STATEMENT) + self.assertEqual(len(rows), 4) + self.assertEqual(rows[0].description, "Opening deposit") + self.assertEqual(rows[0].amount, Decimal("5000.00")) + self.assertEqual(rows[3].category, "") + self.assertEqual(rows[3].line, 6) + + def test_german_file(self): + rows = importer.read_rows(GERMAN, delimiter=";") + self.assertEqual([r.amount for r in rows], [Decimal("-1234.50"), Decimal("2500.00")]) + self.assertEqual(rows[0].date, date(2024, 3, 15)) + + def test_missing_column(self): + with self.assertRaises(ImportFormatError) as ctx: + importer.read_rows("date,amount\n2024-01-01,5\n") + self.assertEqual(ctx.exception.line, 1) + + def test_bad_amount_reports_the_line(self): + with self.assertRaises(ImportFormatError) as ctx: + importer.read_rows("date,description,amount\n2024-01-01,ok,5\n2024-01-02,bad,five\n") + self.assertEqual(ctx.exception.line, 3) + + def test_thousands_with_commas_in_a_file(self): + rows = importer.read_rows('date,description,amount\n2024-01-01,Bonus,"1,500"\n2024-01-02,Car,"(12,345)"\n') + self.assertEqual([r.amount for r in rows], [Decimal("1500"), Decimal("-12345")]) + + +class TransactionTests(unittest.TestCase): + def test_signs_and_default_accounts(self): + txs = importer.load_statement(STATEMENT) + self.assertEqual([tx.id for tx in txs], ["imp-0001", "imp-0002", "imp-0003", "imp-0004"]) + deposit, _invoice, rent, coffee = txs + self.assertEqual([(p.account, str(p.amount.amount)) for p in deposit.postings], + [("1000", "5000.00"), ("3000", "-5000.00")]) + self.assertEqual([(p.account, str(p.amount.amount)) for p in rent.postings], + [("1000", "-800.00"), ("5000", "800.00")]) + self.assertEqual(coffee.postings[1].account, "5900") + + def test_options(self): + txs = importer.load_statement("date,description,amount\n2024-01-01,Gift,10\n", bank="1100", currency="USD", income="4100") + self.assertEqual(txs[0].postings[0].account, "1100") + self.assertEqual(txs[0].postings[1].account, "4100") + self.assertEqual(txs[0].postings[0].amount.currency, "USD") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_journal.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_journal.py new file mode 100644 index 00000000..5f77be5b --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_journal.py @@ -0,0 +1,82 @@ +import unittest +from datetime import date + +from helpers import eur, sample_journal +from ledger import Journal, Money, Transaction, default_chart +from ledger.accounts import UnknownAccount +from ledger.journal import DuplicateTransaction +from ledger.transactions import Posting, UnbalancedTransaction + + +class PostingTests(unittest.TestCase): + def test_post_and_count(self): + self.assertEqual(len(sample_journal()), 7) + + def test_duplicate_id_is_rejected(self): + journal = sample_journal() + again = Transaction.transfer("t1", date(2024, 4, 1), "dup", "1000", "3000", eur("1.00")) + with self.assertRaises(DuplicateTransaction): + journal.post(again) + self.assertEqual(len(journal), 7) + + def test_unknown_account_is_rejected(self): + journal = Journal(default_chart()) + tx = Transaction.transfer("x", date(2024, 1, 1), "bad", "1000", "9999", eur("1.00")) + with self.assertRaises(UnknownAccount): + journal.post(tx) + self.assertEqual(len(journal), 0) + + def test_unbalanced_is_rejected(self): + journal = Journal(default_chart()) + tx = Transaction("x", date(2024, 1, 1), "bad", [Posting("1000", eur("2")), Posting("3000", eur("-1"))]) + with self.assertRaises(UnbalancedTransaction): + journal.post(tx) + + +class QueryTests(unittest.TestCase): + def setUp(self): + self.journal = sample_journal() + + def test_transactions_are_ordered(self): + ids = [tx.id for tx in self.journal.transactions()] + self.assertEqual(ids, ["t1", "t2", "t3", "t4", "t5", "t6", "t7"]) + + def test_date_filter_is_inclusive(self): + found = self.journal.transactions(date(2024, 1, 10), date(2024, 2, 3)) + self.assertEqual([tx.id for tx in found], ["t2", "t3", "t4"]) + + def test_account_filter(self): + found = self.journal.transactions(account="4000") + self.assertEqual([tx.id for tx in found], ["t2", "t5"]) + + def test_balance_as_of_is_inclusive(self): + self.assertEqual(self.journal.balance("1000"), eur("5253.35")) + self.assertEqual(self.journal.balance("1000", date(2024, 1, 15)), eur("5400.00")) + self.assertEqual(self.journal.balance("1000", date(2024, 1, 14)), eur("6200.00")) + + def test_balance_in_other_currency_is_zero(self): + self.assertEqual(self.journal.balance("1000", currency="USD"), Money.zero("USD")) + + def test_natural_balance_flips_credit_accounts(self): + self.assertEqual(self.journal.balance("4000"), eur("-2100.00")) + self.assertEqual(self.journal.natural_balance("4000"), eur("2100.00")) + self.assertEqual(self.journal.natural_balance("5000"), eur("1600.00")) + + def test_movement_in_period(self): + self.assertEqual(self.journal.movement("1000", date(2024, 2, 1), date(2024, 2, 29)), eur("653.35")) + + def test_trial_balance_sums_to_zero(self): + trial = self.journal.trial_balance() + self.assertEqual(sorted(trial), ["1000", "3000", "4000", "5000", "5100", "5200"]) + self.assertEqual(sum((v.amount for v in trial.values())), 0) + + def test_statement_has_running_balance(self): + lines = self.journal.statement("1000") + self.assertEqual([line.tx_id for line in lines], ["t1", "t2", "t3", "t4", "t5", "t6", "t7"]) + self.assertEqual(lines[2].amount, eur("-800.00")) + self.assertEqual(lines[2].balance, eur("5400.00")) + self.assertEqual(lines[-1].balance, eur("5253.35")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_money.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_money.py new file mode 100644 index 00000000..8ca45657 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_money.py @@ -0,0 +1,111 @@ +import unittest +from decimal import Decimal + +from ledger.money import CurrencyMismatch, Money, minor_units + + +def amounts(parts): + return [str(p.amount) for p in parts] + + +class ConstructionTests(unittest.TestCase): + def test_from_str_and_int(self): + self.assertEqual(Money("12.50").amount, Decimal("12.50")) + self.assertEqual(Money(7).amount, Decimal("7")) + + def test_floats_are_rejected(self): + with self.assertRaises(TypeError): + Money(0.1) + + def test_currency_is_upper_cased(self): + self.assertEqual(Money("1", "usd").currency, "USD") + + def test_minor_units(self): + self.assertEqual(minor_units("EUR"), 2) + self.assertEqual(minor_units("jpy"), 0) + self.assertEqual(minor_units("KWD"), 3) + + def test_minor_unit_round_trip(self): + self.assertEqual(Money("12.34").to_minor(), 1234) + self.assertEqual(Money.from_minor(-5), Money("-0.05")) + self.assertEqual(Money("500", "JPY").to_minor(), 500) + self.assertEqual(Money.from_minor(1234, "KWD").amount, Decimal("1.234")) + + def test_sub_unit_amount_has_no_minor_value(self): + with self.assertRaises(ValueError): + Money("0.001").to_minor() + + +class ArithmeticTests(unittest.TestCase): + def test_add_sub_neg_abs(self): + self.assertEqual(Money("1.10") + Money("2.20"), Money("3.30")) + self.assertEqual(Money("1.10") - Money("2.20"), Money("-1.10")) + self.assertEqual(-Money("1.10"), Money("-1.10")) + self.assertEqual(abs(Money("-4.00")), Money("4.00")) + + def test_currency_mismatch(self): + with self.assertRaises(CurrencyMismatch): + Money("1", "EUR") + Money("1", "USD") + with self.assertRaises(CurrencyMismatch): + Money("1", "EUR") < Money("2", "USD") + + def test_comparisons(self): + self.assertTrue(Money("1.00") < Money("1.01")) + self.assertTrue(Money("2.00") >= Money("2.0")) + self.assertFalse(Money("2.00") > Money("2.00")) + + def test_multiply_rounds_to_minor_unit(self): + self.assertEqual(Money("19.99") * Decimal("0.2"), Money("4.00")) + self.assertEqual(3 * Money("0.10"), Money("0.30")) + + def test_multiply_tie_rounds_half_even(self): + self.assertEqual(Money("10.00") * Decimal("0.2675"), Money("2.68")) + self.assertEqual(Money("10.00") * Decimal("0.2665"), Money("2.66")) + + def test_divide(self): + self.assertEqual(Money("10.00") / 3, Money("3.33")) + + def test_str(self): + self.assertEqual(str(Money("1234.5")), "1234.50 EUR") + self.assertEqual(str(Money("-3", "JPY")), "-3 JPY") + + +class AllocateTests(unittest.TestCase): + def test_split_in_three(self): + self.assertEqual(amounts(Money("100.00").split(3)), ["33.34", "33.33", "33.33"]) + + def test_allocate_by_ratio(self): + self.assertEqual(amounts(Money("100.00").allocate([70, 30])), ["70.00", "30.00"]) + self.assertEqual(amounts(Money("0.05").allocate([3, 7])), ["0.02", "0.03"]) + + def test_leftover_goes_to_first_parts_not_largest_remainder(self): + self.assertEqual(amounts(Money("0.07").allocate([3, 1, 6])), ["0.03", "0.00", "0.04"]) + + def test_zero_ratio_gets_nothing(self): + self.assertEqual(amounts(Money("0.01").allocate([0, 1, 1])), ["0.00", "0.01", "0.00"]) + + def test_parts_always_add_up(self): + for cents in (1, 2, 99, 100, 101, 12345): + for ratios in ([1, 1], [1, 1, 1], [5, 3, 2], [1, 2, 3, 4, 5]): + parts = Money.from_minor(cents).allocate(ratios) + self.assertEqual(sum((p.amount for p in parts), Decimal(0)), Decimal(cents) / 100) + + def test_split_without_minor_units(self): + self.assertEqual(amounts(Money("100", "JPY").split(3)), ["34", "33", "33"]) + + def test_negative_amount_split(self): + self.assertEqual(amounts(Money("-100.00").split(3)), ["-33.34", "-33.33", "-33.33"]) + + def test_invalid_arguments(self): + with self.assertRaises(ValueError): + Money("1.00").allocate([]) + with self.assertRaises(ValueError): + Money("1.00").allocate([0, 0]) + with self.assertRaises(ValueError): + Money("1.00").allocate([1, -1]) + with self.assertRaises(ValueError): + Money("1.00").split(0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_reports.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_reports.py new file mode 100644 index 00000000..58d337c1 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_reports.py @@ -0,0 +1,68 @@ +import unittest +from datetime import date + +from helpers import eur, sample_journal, two_year_journal +from ledger import reports + + +class MonthlyTotalsTests(unittest.TestCase): + def test_bank_by_month(self): + totals = reports.monthly_totals(sample_journal(), "1000") + self.assertEqual(list(totals), [date(2024, 1, 1), date(2024, 2, 1), date(2024, 3, 1)]) + self.assertEqual(totals[date(2024, 1, 1)], eur("5400.00")) + self.assertEqual(totals[date(2024, 2, 1)], eur("653.35")) + self.assertEqual(totals[date(2024, 3, 1)], eur("-800.00")) + + def test_period_limits(self): + totals = reports.monthly_totals(sample_journal(), "1000", date(2024, 2, 1), date(2024, 2, 29)) + self.assertEqual(list(totals), [date(2024, 2, 1)]) + + def test_income_account_is_negative(self): + totals = reports.monthly_totals(sample_journal(), "4000") + self.assertEqual(totals[date(2024, 1, 1)], eur("-1200.00")) + + def test_same_month_in_different_years_is_not_merged(self): + totals = reports.monthly_totals(two_year_journal(), "1000") + self.assertEqual(list(totals), [date(2023, 1, 1), date(2023, 12, 1), date(2024, 1, 1)]) + self.assertEqual(totals[date(2023, 1, 1)], eur("2000.00")) + self.assertEqual(totals[date(2024, 1, 1)], eur("1500.00")) + + def test_year_boundary_months_stay_separate(self): + totals = reports.monthly_totals(two_year_journal(), "4000", date(2023, 12, 1), date(2024, 1, 31)) + self.assertEqual(totals[date(2023, 12, 1)], eur("-2100.00")) + self.assertEqual(totals[date(2024, 1, 1)], eur("-2200.00")) + + +class StatementReportTests(unittest.TestCase): + def test_income_statement(self): + result = reports.income_statement(sample_journal(), date(2024, 1, 1), date(2024, 3, 31)) + self.assertEqual(result.income, eur("2100.00")) + self.assertEqual(result.expenses, eur("1846.65")) + self.assertEqual(result.net, eur("253.35")) + self.assertEqual(result.by_account["5000"], eur("1600.00")) + + def test_income_statement_for_one_month(self): + result = reports.income_statement(sample_journal(), date(2024, 2, 1), date(2024, 2, 29)) + self.assertEqual(result.income, eur("900.00")) + self.assertEqual(sorted(result.by_account), ["4000", "5100", "5200"]) + + def test_balance_sheet_balances(self): + sheet = reports.balance_sheet(sample_journal(), date(2024, 3, 31)) + self.assertEqual(sheet["assets"], eur("5253.35")) + self.assertEqual(sheet["liabilities"], eur("0.00")) + self.assertEqual(sheet["equity"], eur("5253.35")) + self.assertEqual(sheet["assets"], sheet["liabilities"] + sheet["equity"]) + + def test_trial_balance_rows(self): + rows = reports.trial_balance_rows(sample_journal(), date(2024, 1, 31)) + by_code = {code: (debit, credit) for code, _name, debit, credit in rows} + self.assertEqual(by_code["1000"], (eur("5400.00"), eur("0"))) + self.assertEqual(by_code["3000"], (eur("0"), eur("5000.00"))) + + def test_top_expenses(self): + top = reports.top_expenses(sample_journal(), date(2024, 1, 1), date(2024, 3, 31), limit=2) + self.assertEqual(top, [("5000", eur("1600.00")), ("5100", eur("150.25"))]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_rounding.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_rounding.py new file mode 100644 index 00000000..e093c302 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_rounding.py @@ -0,0 +1,60 @@ +import unittest +from decimal import Decimal + +from ledger.rounding import quantum, round_decimal, round_half_even, round_to_increment + + +class QuantumTests(unittest.TestCase): + def test_quantum_values(self): + self.assertEqual(quantum(2), Decimal("0.01")) + self.assertEqual(quantum(0), Decimal("1")) + self.assertEqual(quantum(3), Decimal("0.001")) + + +class HalfEvenTests(unittest.TestCase): + def test_ties_go_to_even_digit(self): + self.assertEqual(round_half_even(Decimal("0.125")), Decimal("0.12")) + self.assertEqual(round_half_even(Decimal("0.135")), Decimal("0.14")) + self.assertEqual(round_half_even(Decimal("0.145")), Decimal("0.14")) + + def test_ties_that_floats_cannot_represent(self): + self.assertEqual(round_half_even(Decimal("2.675")), Decimal("2.68")) + self.assertEqual(round_half_even(Decimal("1.015")), Decimal("1.02")) + + def test_not_a_tie(self): + self.assertEqual(round_half_even(Decimal("2.6751")), Decimal("2.68")) + self.assertEqual(round_half_even(Decimal("2.6749")), Decimal("2.67")) + + def test_result_has_requested_places(self): + self.assertEqual(str(round_half_even(Decimal("3"), 2)), "3.00") + self.assertEqual(str(round_half_even(Decimal("2.5"), 0)), "2") + + +class RoundDecimalTests(unittest.TestCase): + def test_modes(self): + value = Decimal("2.675") + self.assertEqual(round_decimal(value, 2, "half_up"), Decimal("2.68")) + self.assertEqual(round_decimal(value, 2, "down"), Decimal("2.67")) + self.assertEqual(round_decimal(value, 2, "up"), Decimal("2.68")) + self.assertEqual(round_decimal(Decimal("-2.671"), 2, "floor"), Decimal("-2.68")) + self.assertEqual(round_decimal(Decimal("-2.679"), 2, "ceiling"), Decimal("-2.67")) + + def test_unknown_mode(self): + with self.assertRaises(ValueError): + round_decimal(Decimal("1.00"), 2, "sideways") + + +class IncrementTests(unittest.TestCase): + def test_cash_rounding(self): + step = Decimal("0.05") + self.assertEqual(round_to_increment(Decimal("1.02"), step), Decimal("1.00")) + self.assertEqual(round_to_increment(Decimal("1.03"), step), Decimal("1.05")) + self.assertEqual(round_to_increment(Decimal("1.075"), step, "down"), Decimal("1.05")) + + def test_increment_must_be_positive(self): + with self.assertRaises(ValueError): + round_to_increment(Decimal("1"), Decimal("0")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_transactions.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_transactions.py new file mode 100644 index 00000000..27149d2e --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_transactions.py @@ -0,0 +1,91 @@ +import unittest +from datetime import date + +from helpers import eur +from ledger.money import Money +from ledger.transactions import Posting, Transaction, UnbalancedTransaction + + +class TransferTests(unittest.TestCase): + def test_transfer_postings(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "Pay rent", "5000", "1000", eur("800.00")) + self.assertEqual([p.account for p in tx.postings], ["5000", "1000"]) + self.assertEqual(tx.postings[0].amount, eur("800.00")) + self.assertEqual(tx.postings[1].amount, eur("-800.00")) + self.assertTrue(tx.is_balanced()) + + def test_date_may_be_an_iso_string(self): + tx = Transaction("t1", "2024-02-29", "x", [Posting("1", eur("1")), Posting("2", eur("-1"))]) + self.assertEqual(tx.date, date(2024, 2, 29)) + + def test_accounts_are_distinct_in_order(self): + tx = Transaction("t1", date(2024, 1, 1), "x", [ + Posting("5000", eur("3")), Posting("1000", eur("-1")), Posting("5000", eur("-2")), + ]) + self.assertEqual(tx.accounts(), ["5000", "1000"]) + self.assertEqual(tx.amount_for("5000"), eur("1")) + + +class ValidationTests(unittest.TestCase): + def test_unbalanced_is_rejected(self): + tx = Transaction("t1", date(2024, 1, 1), "x", [Posting("1", eur("10.00")), Posting("2", eur("-9.99"))]) + self.assertFalse(tx.is_balanced()) + with self.assertRaises(UnbalancedTransaction) as ctx: + tx.validate() + self.assertIn("0.01 EUR", str(ctx.exception)) + + def test_needs_two_postings(self): + tx = Transaction("t1", date(2024, 1, 1), "x", [Posting("1", eur("0"))]) + with self.assertRaises(ValueError): + tx.validate() + + def test_balance_is_checked_per_currency(self): + usd = lambda text: Money(text, "USD") + balanced = Transaction("t1", date(2024, 1, 1), "x", [ + Posting("1", eur("10")), Posting("2", eur("-10")), Posting("3", usd("5")), Posting("4", usd("-5")), + ]) + crossed = Transaction("t2", date(2024, 1, 1), "x", [Posting("1", eur("10")), Posting("2", usd("-10"))]) + self.assertTrue(balanced.is_balanced()) + self.assertEqual(sorted(crossed.imbalance()), ["EUR", "USD"]) + + +class ReversalTests(unittest.TestCase): + def test_reversed_negates_postings(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "Pay rent", "5000", "1000", eur("800.00"), tags=["rent"]) + undo = tx.reversed("t1-r", date(2024, 1, 9)) + self.assertEqual(undo.id, "t1-r") + self.assertEqual(undo.date, date(2024, 1, 9)) + self.assertEqual(undo.description, "Reversal of Pay rent") + self.assertEqual(undo.postings[0].amount, eur("-800.00")) + self.assertEqual(undo.tags, ["rent"]) + self.assertIsNot(undo.tags, tx.tags) + + def test_reversal_defaults_to_same_date(self): + tx = Transaction.transfer("t1", date(2024, 1, 5), "x", "5000", "1000", eur("1.00")) + self.assertEqual(tx.reversed("t1-r").date, date(2024, 1, 5)) + + +class SplitTests(unittest.TestCase): + def test_split_evenly(self): + tx = Transaction.from_split( + "s1", date(2024, 3, 1), "Shared bill", "1000", {"5000": 1, "5100": 1, "5200": 1}, eur("100.00"), + ) + self.assertEqual([str(p.amount.amount) for p in tx.postings], ["33.34", "33.33", "33.33", "-100.00"]) + self.assertTrue(tx.is_balanced()) + + def test_split_by_ratio_gives_extra_cents_to_first_targets(self): + tx = Transaction.from_split( + "s2", date(2024, 3, 1), "Tip", "1000", {"5000": 3, "5100": 1, "5200": 6}, eur("0.07"), + ) + self.assertEqual([str(p.amount.amount) for p in tx.postings], ["0.03", "0.00", "0.04", "-0.07"]) + + def test_refund_split_stays_balanced(self): + tx = Transaction.from_split( + "s3", date(2024, 3, 1), "Refund", "1000", {"5000": 1, "5100": 1, "5200": 1}, eur("-100.00"), + ) + self.assertTrue(tx.is_balanced()) + self.assertEqual([str(p.amount.amount) for p in tx.postings[:3]], ["-33.34", "-33.33", "-33.33"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_utils.py b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_utils.py new file mode 100644 index 00000000..72c4b756 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/seed/tests/test_utils.py @@ -0,0 +1,53 @@ +import unittest +from datetime import date + +from ledger import utils + + +class ChunkedTests(unittest.TestCase): + def test_chunks_of_three(self): + self.assertEqual(list(utils.chunked([1, 2, 3, 4, 5, 6, 7], 3)), [[1, 2, 3], [4, 5, 6], [7]]) + + def test_size_must_be_positive(self): + with self.assertRaises(ValueError): + list(utils.chunked([1], 0)) + + +class GroupByTests(unittest.TestCase): + def test_keeps_first_seen_order(self): + groups = utils.group_by(["bb", "a", "cc", "d", "e"], len) + self.assertEqual(list(groups), [2, 1]) + self.assertEqual(groups[1], ["a", "d", "e"]) + + +class DateHelperTests(unittest.TestCase): + def test_ensure_date(self): + self.assertEqual(utils.ensure_date("2024-03-09"), date(2024, 3, 9)) + self.assertEqual(utils.ensure_date(date(2024, 3, 9)), date(2024, 3, 9)) + + def test_add_months_clamps_day(self): + self.assertEqual(utils.add_months(date(2024, 1, 31), 1), date(2024, 2, 29)) + self.assertEqual(utils.add_months(date(2023, 1, 31), 1), date(2023, 2, 28)) + + def test_add_months_crosses_years(self): + self.assertEqual(utils.add_months(date(2023, 11, 15), 3), date(2024, 2, 15)) + self.assertEqual(utils.add_months(date(2024, 2, 15), -3), date(2023, 11, 15)) + + def test_month_boundaries(self): + self.assertEqual(utils.first_of_month(date(2024, 2, 17)), date(2024, 2, 1)) + self.assertEqual(utils.last_of_month(date(2024, 2, 17)), date(2024, 2, 29)) + self.assertEqual(utils.last_of_month(date(2023, 12, 3)), date(2023, 12, 31)) + + def test_daterange_is_inclusive(self): + days = list(utils.daterange(date(2024, 2, 27), date(2024, 3, 1))) + self.assertEqual(len(days), 4) + self.assertEqual(days[-1], date(2024, 3, 1)) + + def test_clamp(self): + self.assertEqual(utils.clamp(5, 1, 3), 3) + self.assertEqual(utils.clamp(-5, 1, 3), 1) + self.assertEqual(utils.clamp(2, 1, 3), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/fixbug-ledger/task.md b/scripts/e2e/codex/tasks/fixbug-ledger/task.md new file mode 100644 index 00000000..664dc579 --- /dev/null +++ b/scripts/e2e/codex/tasks/fixbug-ledger/task.md @@ -0,0 +1,38 @@ +--- +id: fixbug-ledger +title: Find and fix six seeded bugs in a double-entry ledger library +kind: bugfix +expected_rounds: 15-40 +--- +# Find and fix six seeded bugs in a double-entry ledger library + +Package `ledger/` (13 modules, about 1160 lines) plus 133 visible unittest tests in `tests/` (13 files incl. `helpers.py`). On the seed 13 visible tests fail; +the hidden suite (34 extra cases, `hidden/test_hidden.py`) covers each bug class more broadly. Context grows mainly by reading modules and test output. + +Seeded bugs (one distinct root cause each; reference fix = `reference/overlay/`, restores the original line): + +| module | function | bug | visible failures | +| --- | --- | --- | --- | +| money.py | `Money.allocate` | remainder computed from the signed minor amount, so negative amounts lose cents (also breaks `split`, `Transaction.from_split` for refunds) | 2 | +| rounding.py | `round_half_even` | goes through `float`, ties and long values round wrongly (shows in `Money.__mul__`, `RateTable.convert`) | 3 | +| accounts.py | `Account.__init__` | mutable default argument `labels=[]` shared by all accounts, no copy of the argument | 2 | +| calendar.py | `add_business_days` | rolls a weekend/holiday start to the next business day first, so the result is one business day too late | 2 | +| reports.py | `monthly_totals` | groups by month number only, so January 2023 and January 2024 merge (also visible through `cli monthly`) | 2 | +| importer.py | `_normalise_separators` | a lone comma is always treated as a decimal mark ("1,234" parses as 1.234) | 2 | + +Acceptance (`accept.py`): the pristine `tests/` files (incl. `helpers.py`) are byte-identical; the pristine suite passes (it is run from a clean copy of +`tests/`, extra files the agent added there are ignored); the 34 hidden cases pass; no top-level file shadows a standard module. + +## Prompt + +This repository contains `ledger/`, a small double-entry bookkeeping library (money amounts, chart of accounts, journal, reports, business-day calendar, currency conversion, CSV import/export and a command line tool), with its unit tests in `tests/`. Right now a number of the tests fail. + +Please fix the bugs in the library code so that the whole test suite passes. Run it with `python3 -m unittest discover -s tests`. + +Some notes: +- Do not modify, delete, skip or weaken anything under `tests/`; the tests describe the intended behaviour. +- Several failures may share one root cause, and the existing tests do not cover every input of the buggy code paths. After you find a bug, check the surrounding logic for the same mistake and fix the underlying logic rather than the individual failing inputs. Do not hard-code expected values or stub out functions. +- Keep the code compatible with Python 3.9 or newer and use only the standard library. + +When you are done, reply with a short summary. For each bug you fixed, name the file and function, the root cause, and what you changed. + diff --git a/scripts/e2e/codex/tasks/freeze.py b/scripts/e2e/codex/tasks/freeze.py new file mode 100644 index 00000000..1f22eaa7 --- /dev/null +++ b/scripts/e2e/codex/tasks/freeze.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Rewrite tasks/MANIFEST.sha256 (see delta/taskfile.py). Run after selftest.py, commit, then install read-only on the server.""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..", "delta")) +import taskfile # noqa: E402 + +lines = taskfile.manifest_lines(HERE) +with open(os.path.join(HERE, "MANIFEST.sha256"), "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(lines) + "\n") +print("%d manifest lines for %d tasks" % (len(lines), len(taskfile.task_ids(HERE)))) diff --git a/scripts/e2e/codex/tasks/refactor-shop/accept.py b/scripts/e2e/codex/tasks/refactor-shop/accept.py new file mode 100644 index 00000000..0de4230a --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/accept.py @@ -0,0 +1,421 @@ +#!/usr/bin/env python3 +"""Acceptance for refactor-shop. Usage: python3 accept.py WORKSPACE + +Exit 0 = every check passed. The workspace is copied to a private temporary directory first and is +never modified. Standard library only; runs on Python 3.9 .. 3.14. +""" + +import ast +import os +import re +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +HIDDEN = os.path.join(HERE, "hidden") + +RESULTS = [] # (ok, name, detail) + + +def record(ok, name, detail=""): + RESULTS.append((bool(ok), name, detail)) + print(("PASS %s" % name) if ok else ("FAIL %s :: %s" % (name, " ".join(str(detail).split())[:400]))) + + +def check(name): + """Decorator: run a check function; an exception or a returned string means failure.""" + + def deco(fn): + try: + problem = fn() + except Exception as exc: # noqa: BLE001 - any crash of a check is a failed check + record(False, name, "%s: %s" % (type(exc).__name__, exc)) + else: + record(problem is None, name, problem or "") + return fn + + return deco + + +# ------------------------------------------------------------------------------------------ helpers + + +def parse(path): + with open(path, encoding="utf-8") as fh: + text = fh.read() + return ast.parse(text, filename=path), text + + +def shop_modules(root): + """{module file name: (tree, text)} for every shop/*.py.""" + result = {} + folder = os.path.join(root, "shop") + for name in sorted(os.listdir(folder)): + if name.endswith(".py"): + result[name] = parse(os.path.join(folder, name)) + return result + + +def defined_functions(tree): + return {n.name for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} + + +def referenced_names(tree): + names = set() + for n in ast.walk(tree): + if isinstance(n, ast.Name): + names.add(n.id) + elif isinstance(n, ast.Attribute): + names.add(n.attr) + elif isinstance(n, (ast.ImportFrom, ast.Import)): + for alias in n.names: + names.add(alias.name.split(".")[-1]) + if isinstance(n, ast.ImportFrom) and n.module: + names.add(n.module.split(".")[-1]) + return names + + +def call_name(node): + f = node.func + if isinstance(f, ast.Name): + return f.id + if isinstance(f, ast.Attribute): + return f.attr + return None + + +def contains_number(node): + for n in ast.walk(node): + if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) and not isinstance(n.value, bool): + return True + if isinstance(n, ast.Call) and call_name(n) == "Decimal": + return True + return False + + +def is_frozen_dataclass(cls): + for dec in cls.decorator_list: + target = dec.func if isinstance(dec, ast.Call) else dec + name = target.id if isinstance(target, ast.Name) else getattr(target, "attr", None) + if name == "dataclass": + if isinstance(dec, ast.Call): + for kw in dec.keywords: + if kw.arg == "frozen" and isinstance(kw.value, ast.Constant) and kw.value.value is True: + return True + return False + + +def class_fields(cls): + return [n.target.id for n in cls.body if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)] + + +def run(cmd, cwd, timeout=300, env_extra=None): + env = dict(os.environ) + env.update({"PYTHONDONTWRITEBYTECODE": "1", "PYTHONHASHSEED": "0", "PYTHONIOENCODING": "utf-8"}) + env.pop("PYTHONPATH", None) + if env_extra: + env.update(env_extra) + return subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) + + +# ----------------------------------------------------------------------------------------- the checks + + +def main(): + if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]): + print("usage: accept.py WORKSPACE", file=sys.stderr) + return 2 + workspace = os.path.abspath(sys.argv[1]) + tmp = tempfile.mkdtemp(prefix="accept-refactor-shop-") + root = os.path.join(tmp, "ws") + try: + shutil.copytree( + workspace, root, ignore=shutil.ignore_patterns("__pycache__", ".git", "*.pyc", ".pytest_cache", ".mypy_cache") + ) + evaluate(root, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + failed = [r for r in RESULTS if not r[0]] + print("%d checks, %d failed" % (len(RESULTS), len(failed))) + return 1 if failed else 0 + + +def evaluate(root, tmp): + if not os.path.isdir(os.path.join(root, "shop")): + record(False, "layout", "no shop/ package in the workspace") + return + + try: + modules = shop_modules(root) + except SyntaxError as exc: + record(False, "syntax", "shop/ does not parse: %s" % exc) + return + others = {k: v for k, v in modules.items()} + + # ---- pristine tests (with the textual rename applied) must pass + @check("pristine_tests_pass") + def _(): + probe = os.path.join(tmp, "probe") + shutil.copytree(root, probe) + shutil.rmtree(os.path.join(probe, "tests"), ignore_errors=True) + shutil.copytree(os.path.join(HIDDEN, "tests"), os.path.join(probe, "tests")) + for dirpath, _dirs, files in os.walk(os.path.join(probe, "tests")): + for fname in files: + if fname.endswith(".py"): + path = os.path.join(dirpath, fname) + with open(path, encoding="utf-8") as fh: + text = fh.read() + with open(path, "w", encoding="utf-8", newline="") as fh: + fh.write(re.sub(r"\bCust\b", "Customer", text)) + proc = run([sys.executable, "-m", "unittest", "discover", "-s", "tests"], probe) + out = proc.stdout.decode("utf-8", "replace") + m = re.search(r"Ran (\d+) tests?", out) + if proc.returncode != 0 or not m: + tail = [l for l in out.splitlines() if l.strip()][-6:] + return "unittest exit %s: %s" % (proc.returncode, " | ".join(tail)) + if int(m.group(1)) < 100: + return "only %s tests ran" % m.group(1) + return None + + # ---- step 1 + @check("s1_pricing_module") + def _(): + path = os.path.join(root, "shop", "pricing.py") + if not os.path.exists(path): + return "shop/pricing.py is missing" + tree, _text = modules["pricing.py"] + if "price_order" not in {n.name for n in tree.body if isinstance(n, ast.FunctionDef)}: + return "price_order is not a module-level function of pricing.py" + cls = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "PriceBreakdown"] + if not cls: + return "class PriceBreakdown missing" + if not is_frozen_dataclass(cls[0]): + return "PriceBreakdown is not a frozen dataclass" + missing = {"subtotal", "discount", "tax", "shipping", "total"} - set(class_fields(cls[0])) + return "PriceBreakdown lacks fields %s" % sorted(missing) if missing else None + + @check("s1_duplicates_deleted") + def _(): + gone = {"calc_total", "compute_order_total", "order_total_with_tax"} + for name, (tree, _t) in modules.items(): + defined = defined_functions(tree) & gone + used = referenced_names(tree) & gone + if defined or used: + return "%s still has %s" % (name, sorted(defined | used)) + return None + + @check("s1_modules_use_price_order") + def _(): + for name in ("invoices.py", "reports.py", "loyalty.py", "returns.py"): + if name not in modules: + return "%s is missing" % name + refs = referenced_names(modules[name][0]) + if "price_order" not in refs and "pricing" not in refs: + return "%s does not use pricing.price_order" % name + return None + + @check("s1_no_inline_rounding") + def _(): + for name, (tree, _t) in modules.items(): + if name in ("currency.py", "pricing.py"): + continue + for n in ast.walk(tree): + if isinstance(n, ast.Call) and call_name(n) == "quantize": + return "%s rounds with .quantize() itself" % name + tree = modules["invoices.py"][0] + for n in ast.walk(tree): + if isinstance(n, ast.Call) and call_name(n) == "money": + return "invoices.py still rounds money amounts inline" + return None + + # ---- step 2 + @check("s2_config_module") + def _(): + if "config.py" not in modules: + return "shop/config.py is missing" + tree, _t = modules["config.py"] + cls = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "Config"] + if not cls or not is_frozen_dataclass(cls[0]): + return "Config is missing or not a frozen dataclass" + assigned = set() + for n in tree.body: + if isinstance(n, ast.Assign): + assigned |= {t.id for t in n.targets if isinstance(t, ast.Name)} + elif isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name): + assigned.add(n.target.id) + return None if "DEFAULT_CONFIG" in assigned else "DEFAULT_CONFIG is not defined" + + @check("s2_no_numeric_constants_outside_config") + def _(): + pattern = re.compile(r"^_?[A-Z][A-Z0-9_]*$") + for name, (tree, _t) in modules.items(): + if name in ("config.py", "sample.py"): + continue + for node in tree.body: + if isinstance(node, ast.Assign): + targets, value = node.targets, node.value + elif isinstance(node, ast.AnnAssign) and node.value is not None: + targets, value = [node.target], node.value + else: + continue + for t in targets: + if isinstance(t, ast.Name) and pattern.match(t.id) and contains_number(value): + return "%s defines %s" % (name, t.id) + return None + + # ---- step 3 + @check("s3_customer_rename") + def _(): + tree = modules["customers.py"][0] + if "Customer" not in {n.name for n in tree.body if isinstance(n, ast.ClassDef)}: + return "class Customer is not defined in customers.py" + pattern = re.compile(r"\bCust\b") + for name, (_tree, text) in modules.items(): + if pattern.search(text): + return "%s still mentions Cust" % name + tests_dir = os.path.join(root, "tests") + if os.path.isdir(tests_dir): + for fname in sorted(os.listdir(tests_dir)): + if fname.endswith(".py"): + with open(os.path.join(tests_dir, fname), encoding="utf-8") as fh: + if pattern.search(fh.read()): + return "tests/%s still mentions Cust" % fname + return None + + # ---- step 4 + @check("s4_reports_do_not_print") + def _(): + tree, text = modules["reports.py"] + for n in ast.walk(tree): + if isinstance(n, ast.Call) and call_name(n) == "print": + return "reports.py calls print (line %d)" % n.lineno + if isinstance(n, ast.Attribute) and n.attr in ("stdout", "stderr"): + return "reports.py touches sys.%s" % n.attr + names = defined_functions(tree) + need = {"sales_report", "customer_report", "inventory_report", "tax_summary", "aging_report"} + return "missing %s" % sorted(need - names) if need - names else None + + @check("s4_cli_prints") + def _(): + tree = modules["cli.py"][0] + prints = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and call_name(n) == "print"] + return None if prints else "cli.py never prints" + + # ---- step 5 + @check("s5_single_date_parser") + def _(): + if "dates.py" not in modules: + return "shop/dates.py is missing" + if "parse_date" not in {n.name for n in modules["dates.py"][0].body if isinstance(n, ast.FunctionDef)}: + return "parse_date is not defined in dates.py" + old = {"parse_joined", "parse_order_date", "parse_due_date", "_to_date"} + for name, (tree, _t) in modules.items(): + found = (defined_functions(tree) | referenced_names(tree)) & old + if found: + return "%s still has %s" % (name, sorted(found)) + if name == "dates.py": + continue + for n in ast.walk(tree): + if not isinstance(n, ast.Call): + continue + cn = call_name(n) + if cn in ("strptime", "fromisoformat"): + return "%s calls %s (line %d)" % (name, cn, n.lineno) + if cn in ("date", "datetime") and (n.args or n.keywords): + return "%s builds a date by hand with %s(...) (line %d)" % (name, cn, n.lineno) + return None + + # ---- step 6 + @check("s6_dead_code_removed") + def _(): + dead = {"legacy_price_lookup", "dump_stock_csv", "old_order_summary", "estimate_zone_v1", "slugify"} + for name, (tree, _t) in modules.items(): + found = (defined_functions(tree) | referenced_names(tree)) & dead + if found: + return "%s still has %s" % (name, sorted(found)) + return None + + # ---- step 7 + @check("s7_hints_and_docstrings") + def _(): + for fname in ("pricing.py", "config.py", "dates.py"): + if fname not in modules: + return "%s is missing" % fname + tree = modules[fname][0] + public = [] + for n in tree.body: + if isinstance(n, ast.ClassDef) and not n.name.startswith("_"): + if not ast.get_docstring(n): + return "%s: class %s has no docstring" % (fname, n.name) + public += [m for m in n.body if isinstance(m, ast.FunctionDef) and not m.name.startswith("_")] + elif isinstance(n, ast.FunctionDef) and not n.name.startswith("_"): + public.append(n) + if fname != "config.py" and not public: + return "%s has no public function" % fname + for fn in public: + if not ast.get_docstring(fn): + return "%s: %s has no docstring" % (fname, fn.name) + if fn.returns is None: + return "%s: %s has no return annotation" % (fname, fn.name) + args = fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs + if fn.args.vararg: + args.append(fn.args.vararg) + if fn.args.kwarg: + args.append(fn.args.kwarg) + for a in args: + if a.arg in ("self", "cls"): + continue + if a.annotation is None: + return "%s: argument %s of %s has no annotation" % (fname, a.arg, fn.name) + return None + + # ---- step 8 + @check("s8_architecture_doc") + def _(): + path = os.path.join(root, "docs", "ARCHITECTURE.md") + if not os.path.exists(path): + return "docs/ARCHITECTURE.md is missing" + with open(path, encoding="utf-8") as fh: + text = fh.read() + for need in ("pricing.py", "config.py", "dates.py", "price_order", "Customer"): + if need not in text: + return "does not mention %s" % need + gone = [ + "calc_total", "compute_order_total", "order_total_with_tax", "parse_joined", "parse_order_date", + "parse_due_date", "_to_date", "legacy_price_lookup", "dump_stock_csv", "old_order_summary", + "estimate_zone_v1", "slugify", "TAX_RATE", "FREE_SHIPPING_THRESHOLD", "TIER_RATES", "REGION_RATES", + "VOLUME_DISCOUNT_RATE", "RESTOCKING_FEE_RATE", + ] + for word in gone: + if re.search(r"(?= cfg.volume_min_qty), D("0")) + tier = q2((sub - vol) * cfg.tier_rates.get(order.customer.tier, D("0"))) + base = sub - vol - tier + code = (order.coupon or "").upper() + coupon = D("0") + if code in cfg.coupon_percent: + coupon = q2(base * cfg.coupon_percent[code]) + elif code in cfg.coupon_flat and sub >= cfg.coupon_flat_min_subtotal: + coupon = min(cfg.coupon_flat[code], base) + discount = vol + tier + coupon + net = sub - discount + rate = D("0") if order.customer.tax_exempt else cfg.region_tax_rates.get(order.ship_country, cfg.default_tax_rate) + tax = q2(net * rate) + ship = D("0") + if order.lines and net < cfg.free_shipping_threshold: + ship = cfg.shipping_flat + if weight > cfg.free_weight_kg: + ship += q2((weight - cfg.free_weight_kg) * cfg.shipping_per_kg) + if order.ship_country != cfg.home_country: + ship += cfg.international_surcharge + return (sub, discount, tax, ship, net + tax + ship) + + +def make_order(rng, idx=0): + from shop.customers import Customer + from shop.orders import add_line, new_order + from shop.products import get_product + + cust = Customer("h%d" % idx, "Hidden %d" % idx, "h@example.org", rng.choice(TIERS), rng.choice(COUNTRIES), + date(2021, 5, 17), rng.random() < 0.15) + order = new_order("H-%03d" % idx, cust, coupon=rng.choice(COUPONS), ship_country=rng.choice(COUNTRIES), + placed_on=date(2024, 5, 1 + idx % 27)) + for sku in rng.sample(SKUS, rng.randint(1, 4)): + add_line(order, get_product(sku), rng.randint(1, 14)) + return order + + +def random_config(rng): + from shop.config import DEFAULT_CONFIG + + return dataclasses.replace( + DEFAULT_CONFIG, + home_country=rng.choice(["DE", "FR", "US"]), + default_tax_rate=rng.choice([D("0.10"), D("0.19"), D("0.23")]), + region_tax_rates={"FR": D("0.055"), "US": D("0.0825"), "SE": D("0.12")}, + free_shipping_threshold=rng.choice([D("20"), D("60"), D("100"), D("250")]), + shipping_flat=rng.choice([D("3.99"), D("6.50"), D("12")]), + free_weight_kg=rng.choice([D("1"), D("5"), D("20")]), + shipping_per_kg=rng.choice([D("0.35"), D("1.20"), D("2.5")]), + international_surcharge=rng.choice([D("0"), D("8.00"), D("15.25")]), + volume_min_qty=rng.choice([3, 5, 10]), + volume_rate=rng.choice([D("0.02"), D("0.05"), D("0.125")]), + tier_rates={"bronze": D("0.01"), "silver": D("0.04"), "gold": D("0.08"), "platinum": D("0.15")}, + coupon_percent={"WELCOME10": D("0.20"), "SPRING15": D("0.15")}, + coupon_flat={"SAVE5": D("9.99"), "BULK20": D("35")}, + coupon_flat_min_subtotal=rng.choice([D("30"), D("50"), D("120")]), + ) + + +def demo(): + from shop.sample import load_demo + + return load_demo() + + +# ----------------------------------------------------------------------------------------------- checks + + +def check_config_defaults(): + from shop.config import DEFAULT_CONFIG, Config + + assert isinstance(DEFAULT_CONFIG, Config), "DEFAULT_CONFIG is not a Config" + assert Config() == DEFAULT_CONFIG, "Config() != DEFAULT_CONFIG" + assert dataclasses.is_dataclass(Config), "Config is not a dataclass" + names = {f.name for f in dataclasses.fields(Config)} + missing = set(EXPECTED_DEFAULTS) - names + assert not missing, "missing fields: %s" % sorted(missing) + for key, want in EXPECTED_DEFAULTS.items(): + got = getattr(DEFAULT_CONFIG, key) + assert got == want, "%s: %r != %r" % (key, got, want) + if isinstance(want, Decimal): + assert isinstance(got, Decimal), "%s is %s, not Decimal" % (key, type(got).__name__) + try: + DEFAULT_CONFIG.shipping_flat = D("1") + except dataclasses.FrozenInstanceError: + pass + else: + raise AssertionError("Config is not frozen") + other = dataclasses.replace(DEFAULT_CONFIG, shipping_flat=D("1")) + assert other.shipping_flat == D("1") and DEFAULT_CONFIG.shipping_flat == D("6.50") + + +def check_price_order_demo(): + from shop.config import DEFAULT_CONFIG + from shop.pricing import PriceBreakdown, price_order + + _c, orders, _inv = demo() + for order, want in zip(orders, DEMO_PRICES): + for cfg_args in ((), (DEFAULT_CONFIG,)): + p = price_order(order, *cfg_args) + assert isinstance(p, PriceBreakdown), "not a PriceBreakdown" + got = (p.subtotal, p.discount, p.tax, p.shipping, p.total) + assert all(isinstance(v, Decimal) for v in got), "amounts are not all Decimal" + assert got == tuple(D(v) for v in want), "%s: %s != %s" % (order.order_id, got, want) + try: + p.total = D("1") + except dataclasses.FrozenInstanceError: + pass + else: + raise AssertionError("PriceBreakdown is not frozen") + assert [f.name for f in dataclasses.fields(PriceBreakdown)] == ["subtotal", "discount", "tax", "shipping", "total"] + + +def check_price_order_empty_and_edges(): + from helpers_h import order_with + from shop.pricing import price_order + + p = price_order(order_with([])) + assert (p.subtotal, p.discount, p.tax, p.shipping, p.total) == (D(0), D(0), D(0), D(0), D(0)), p + p = price_order(order_with([("P-101", 5), ("P-111", 7)])) # exactly 100.00 net: free shipping + assert p.shipping == D(0) and p.total == D("119.00"), p + p = price_order(order_with([("P-101", 4), ("P-111", 7)])) + assert p.shipping == D("6.50") and p.tax == D("18.39"), p + p = price_order(order_with([("P-106", 2)], country="US", exempt=True)) + assert p.tax == D(0) and p.shipping == D("15.22"), p + + +def check_price_order_random_configs(): + from shop.config import DEFAULT_CONFIG + from shop.pricing import price_order + + rng = random.Random(20241030) + for i in range(400): + order = make_order(rng, i) + cfg = DEFAULT_CONFIG if i % 4 == 0 else random_config(rng) + p = price_order(order, cfg) + got = (p.subtotal, p.discount, p.tax, p.shipping, p.total) + want = oracle(order, cfg) + assert got == want, "order %d (%s %s %s): %s != %s" % (i, order.customer.tier, order.ship_country, order.coupon, got, want) + + +def check_wrappers_follow_config(): + from shop.config import DEFAULT_CONFIG + from shop.discounts import describe_discount, discount_for_order + from shop.shipping import is_free_shipping, shipping_cost + from shop.tax import rate_for, tax_breakdown, tax_for_order + + rng = random.Random(99) + _c, orders, _inv = demo() + for i in range(60): + order = make_order(rng, i) + cfg = random_config(rng) + want = oracle(order, cfg) + assert discount_for_order(order, config=cfg) == want[1], "discount_for_order" + assert tax_for_order(order, config=cfg) == want[2], "tax_for_order" + assert shipping_cost(order, config=cfg) == want[3], "shipping_cost" + assert is_free_shipping(order, config=cfg) == (want[0] - want[1] >= cfg.free_shipping_threshold), "is_free_shipping" + assert isinstance(describe_discount(order, config=cfg), str) + cfg = dataclasses.replace(DEFAULT_CONFIG, default_tax_rate=D("0.5"), region_tax_rates={"US": D("0.01")}) + assert rate_for("DE", config=cfg) == D("0.5") and rate_for("US", config=cfg) == D("0.01") + assert rate_for("US", orders[4].customer, config=cfg) == D(0) + sums = tax_breakdown(orders, config=cfg) + assert sums["US"] == sum((oracle(o, cfg)[2] for o in orders if o.ship_country == "US"), D(0)), sums + cfg2 = dataclasses.replace(cfg, volume_rate=D("0.5"), volume_min_qty=2) + assert describe_discount(orders[5], config=cfg2).startswith("volume "), describe_discount(orders[5], config=cfg2) + + +def check_invoice_uses_config(): + import dataclasses as dc + from shop.config import DEFAULT_CONFIG + from shop.invoices import build_invoice + + rng = random.Random(5) + for i in range(40): + order = make_order(rng, i) + cfg = dc.replace(random_config(rng), invoice_due_days=rng.choice([7, 30, 45])) + inv = build_invoice(order, config=cfg) + want = oracle(order, cfg) + assert (inv.subtotal, inv.discount, inv.tax, inv.shipping, inv.total) == want, "invoice amounts" + issued = order.placed_on + assert inv.issued == issued.isoformat() + delta = (datetime.strptime(inv.due, "%Y-%m-%d").date() - issued).days + assert delta == cfg.invoice_due_days, "due after %d days, wanted %d" % (delta, cfg.invoice_due_days) + order = make_order(rng, 3) + assert build_invoice(order).total == oracle(order, DEFAULT_CONFIG)[4] + + +def check_services_use_config(): + from helpers_h import order_with + from shop.config import DEFAULT_CONFIG + from shop.customers import suggest_tier + from shop.inventory import Inventory, low_stock + from shop.loyalty import points_for_order, redeem_value + from shop.returns import can_return, refund_amount + from shop.validation import validate_order + + cfg = dataclasses.replace( + DEFAULT_CONFIG, + loyalty_points_per_unit=3, + loyalty_multipliers={"bronze": D("2"), "gold": D("4")}, + loyalty_point_value=D("0.05"), + low_stock_threshold=20, + return_window_days=10, + restocking_fee_rate=D("0.50"), + max_line_qty=5, + max_order_lines=1, + tier_spend_thresholds={"silver": D("10"), "gold": D("20"), "platinum": D("30")}, + ) + order = order_with([("P-102", 2)]) # 49.80 net, bronze + assert points_for_order(order, config=cfg) == int(D("49.80") * 3 * 2) == 298 + assert points_for_order(order) == 49 + assert redeem_value(100, config=cfg) == D("5.00") and redeem_value(100) == D("1.00") + inv = Inventory({"P-100": 20, "P-101": 21}) + assert low_stock(inv, config=cfg) == ["P-100"] and low_stock(inv) == [] + assert low_stock(inv, 100, config=cfg) == ["P-100", "P-101"], "explicit threshold must win" + assert can_return(order, date(2024, 3, 11), config=cfg) and not can_return(order, date(2024, 3, 12), config=cfg) + assert can_return(order, date(2024, 3, 12)) + one = order_with([("P-104", 1)]) # net 18.75, tax 3.5625 -> 3.56; base 22.31 + assert refund_amount(one, "P-104", 1) == D("20.08"), refund_amount(one, "P-104", 1) + assert refund_amount(one, "P-104", 1, config=cfg) == D("11.15"), refund_amount(one, "P-104", 1, config=cfg) + big = order_with([("P-100", 6), ("P-101", 1)]) + assert validate_order(big) == [] + assert validate_order(big, config=cfg) == ["too many lines: 2", "P-100: quantity 6 exceeds 5"], validate_order(big, config=cfg) + assert suggest_tier(D("25"), config=cfg) == "gold" and suggest_tier(D("25")) == "bronze" + + +def check_other_modules_use_config(): + from shop.analytics import average_order_value, best_customers, revenue_by_month + from shop.cart import Cart + from shop.config import DEFAULT_CONFIG + from shop.export import orders_to_csv + from shop.notifications import order_confirmation + from shop.orders import order_summary + + _c, orders, _inv = demo() + cfg = dataclasses.replace(DEFAULT_CONFIG, default_tax_rate=D("0.40"), free_shipping_threshold=D("1000")) + totals = [oracle(o, cfg)[4] for o in orders] + assert revenue_by_month(orders, config=cfg) == {"2024-03": sum(totals, D(0))} + assert average_order_value(orders, config=cfg) == q2(sum(totals, D(0)) / len(totals)) + top = best_customers(orders, 1, config=cfg)[0] + spend = {} + for o in orders: + w = oracle(o, cfg) + spend[o.customer.cid] = spend.get(o.customer.cid, D(0)) + w[0] - w[1] + w[2] + assert top == sorted(spend.items(), key=lambda kv: (-kv[1], kv[0]))[0], top + row = orders_to_csv(orders[:1], config=cfg).splitlines()[1].split(",") + assert row[-1] == str(q2(totals[0])) and row[-2] == str(q2(oracle(orders[0], cfg)[3])), row + assert str(q2(totals[1])) in order_summary(orders[1], config=cfg) + assert str(q2(totals[2])) in order_confirmation(orders[2], config=cfg) + cart = Cart(orders[3].customer, coupon="SPRING15") + cart.add("P-107", 4) + cart.add("P-105", 1) + est = cart.estimate(config=cfg) + want = oracle(cart.to_order("X"), cfg) + assert (est["tax"], est["shipping"], est["total"]) == (want[2], want[3], want[4]), est + assert est["net"] == want[0] - want[1] + + +def _silent(fn, *args, **kwargs): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + result = fn(*args, **kwargs) + return result, buf.getvalue() + + +def check_reports_return_text(): + from shop import reports + from shop.config import DEFAULT_CONFIG + from shop.invoices import build_invoice + from shop.products import default_catalog + + customers, orders, inv = demo() + invoices = [build_invoice(o) for o in orders] + calls = [ + ("sales_report", (orders,)), + ("customer_report", (customers, orders)), + ("inventory_report", (inv, default_catalog())), + ("tax_summary", (orders,)), + ("aging_report", (invoices, "2024-04-10")), + ] + for name, args in calls: + text, printed = _silent(getattr(reports, name), *args) + assert isinstance(text, str), "%s returned %s" % (name, type(text).__name__) + assert printed == "", "%s printed %r" % (name, printed[:40]) + assert text and not text.endswith("\n"), "%s: bad trailing newline" % name + again, _ = _silent(getattr(reports, name), *args, config=DEFAULT_CONFIG) + assert again == text, "%s differs with explicit default config" % name + assert reports.sales_report(orders).splitlines()[0] == "SALES REPORT" + cfg = dataclasses.replace(DEFAULT_CONFIG, default_tax_rate=D("0.30"), region_tax_rates={}) + totals = sum((oracle(o, cfg)[4] for o in orders), D(0)) + last = reports.sales_report(orders, config=cfg).splitlines() + assert last[-2].split()[-1] == "{:,.2f}".format(totals), last[-2] + tax_lines = reports.tax_summary(orders, config=cfg).splitlines() + assert tax_lines[-1].split()[-1] == "{:,.2f}".format(sum((oracle(o, cfg)[2] for o in orders), D(0))), tax_lines[-1] + cfg7 = dataclasses.replace(DEFAULT_CONFIG, aging_bucket_days=5, low_stock_threshold=500, tier_spend_thresholds={"silver": D(1), "gold": D(2), "platinum": D(3)}) + aging = reports.aging_report(invoices, "2024-04-10", config=cfg7).splitlines() + assert aging[2].endswith("over 5 days"), aging[2] + low = reports.inventory_report(inv, default_catalog(), config=cfg7) + assert low.count(" LOW") >= 10, "inventory_report ignores low_stock_threshold" + assert "suggest platinum" in reports.customer_report(customers, orders, config=cfg7) + + +def check_cli_prints_reports(): + from shop.cli import main + + for argv in (["report", "sales"], ["report", "tax"], ["report", "customers"], ["report", "inventory"], + ["report", "aging", "2024-04-10"]): + code, out = _silent(main, argv) + assert code == 0 and out.endswith("\n") and not out.endswith("\n\n"), argv + assert out.count("\n") >= 5, argv + + +def check_parse_date(): + from shop.dates import parse_date + + good = { + "2024-03-05": date(2024, 3, 5), + " 2024-03-05\n": date(2024, 3, 5), + "2024/03/05": date(2024, 3, 5), + "05.03.2024": date(2024, 3, 5), + "5.3.2024": date(2024, 3, 5), + "05/03/2024": date(2024, 3, 5), + "7/12/2023": date(2023, 12, 7), + "Mar 5, 2024": date(2024, 3, 5), + "mar 5, 2024": date(2024, 3, 5), + "Dec 24, 2023": date(2023, 12, 24), + "29.02.2024": date(2024, 2, 29), + "2024-02-29": date(2024, 2, 29), + "31/12/1999": date(1999, 12, 31), + } + for text, want in good.items(): + got = parse_date(text) + assert type(got) is date and got == want, "%r -> %r, wanted %r" % (text, got, want) + for bad in ["", "yesterday", "2024-02-30", "31.04.2024", "2024-13-01", "Foo 5, 2024", "20240305", "2024-03", "29.02.2023"]: + try: + got = parse_date(bad) + except ValueError: + continue + raise AssertionError("%r parsed as %r instead of raising ValueError" % (bad, got)) + + +def check_customer_class_and_dates_in_loaders(): + import shop.customers as customers_mod + from shop.customers import Customer, load_customers + from shop.storage import parse_orders + + assert not hasattr(customers_mod, "Cust"), "Cust still exists" + assert dataclasses.is_dataclass(Customer) + assert [f.name for f in dataclasses.fields(Customer)] == ["cid", "name", "email", "tier", "country", "joined", "tax_exempt"] + cs = load_customers("c1, A, a@example.org, gold, DE, 2020-02-29, 0\nc2, B, b@example.org, , FR, , 1") + assert cs[0].joined == date(2020, 2, 29) and cs[1].joined is None and cs[1].tax_exempt and cs[1].tier == "bronze" + os_ = parse_orders("O-1; c1; P-100:1; ; DE; 5.3.2024\nO-2; c2; P-100:1; ; DE; 2024/03/05", cs) + assert os_[0].placed_on == os_[1].placed_on == date(2024, 3, 5), os_ + + +CHECKS = [ + check_config_defaults, + check_price_order_demo, + check_price_order_empty_and_edges, + check_price_order_random_configs, + check_wrappers_follow_config, + check_invoice_uses_config, + check_services_use_config, + check_other_modules_use_config, + check_reports_return_text, + check_cli_prints_reports, + check_parse_date, + check_customer_class_and_dates_in_loaders, +] + + +def main(): + for fn in CHECKS: + name = fn.__name__[len("check_"):] + try: + fn() + print("PASS %s" % name) + except AssertionError as exc: + print("FAIL %s :: %s" % (name, " ".join(str(exc).split())[:300])) + except Exception as exc: # noqa: BLE001 - report any crash as a failed check + tb = traceback.extract_tb(exc.__traceback__)[-1] + print("FAIL %s :: %s: %s (%s:%d)" % (name, type(exc).__name__, " ".join(str(exc).split())[:200], tb.filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1], tb.lineno)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/helpers_h.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/helpers_h.py new file mode 100644 index 00000000..8a1f67be --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/helpers_h.py @@ -0,0 +1,15 @@ +"""Order construction helper for the hidden checks (independent of the visible tests).""" + +from datetime import date + +from shop.customers import Customer +from shop.orders import add_line, new_order +from shop.products import get_product + + +def order_with(items, tier="bronze", country="DE", coupon=None, exempt=False, placed_on=date(2024, 3, 1)): + cust = Customer("h900", "Hidden Buyer", "h900@example.org", tier, country, date(2020, 1, 1), exempt) + order = new_order("H-1", cust, coupon=coupon, ship_country=country, placed_on=placed_on) + for sku, qty in items: + add_line(order, get_product(sku), qty) + return order diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/helpers.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/helpers.py new file mode 100644 index 00000000..5d662c92 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/helpers.py @@ -0,0 +1,42 @@ +import contextlib +import io +from datetime import date + +from shop.cli import main +from shop.customers import Cust +from shop.orders import add_line, new_order +from shop.products import get_product + + +def customer(cid="c900", tier="bronze", country="DE", exempt=False): + return Cust(cid, "Test " + cid, cid + "@example.org", tier, country, date(2020, 1, 1), exempt) + + +def order_with(items, tier="bronze", country="DE", coupon=None, exempt=False, order_id="T-1", placed_on=date(2024, 3, 1)): + order = new_order( + order_id, + customer(tier=tier, country=country, exempt=exempt), + coupon=coupon, + ship_country=country, + placed_on=placed_on, + ) + for sku, qty in items: + add_line(order, get_product(sku), qty) + return order + + +def run_cli(*argv): + """Run the command line tool, return (exit code, stdout).""" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(list(argv)) + return code, buf.getvalue() + + +def render(fn, *args, **kwargs): + """Text produced by a report function, whether it returns it or prints it.""" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + result = fn(*args, **kwargs) + text = result if isinstance(result, str) else buf.getvalue() + return text.rstrip("\n") diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_discounts.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_discounts.py new file mode 100644 index 00000000..4924692d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_discounts.py @@ -0,0 +1,64 @@ +import unittest +from decimal import Decimal + +from helpers import order_with +from shop.discounts import describe_discount, discount_for_order +from shop.sample import load_demo + + +class DiscountTests(unittest.TestCase): + def test_volume_discount_on_large_line(self): + order = order_with([("P-100", 10)]) + self.assertEqual(discount_for_order(order), Decimal("2.25")) + self.assertEqual(describe_discount(order), "volume 2.25") + + def test_no_volume_discount_below_ten(self): + order = order_with([("P-100", 9)]) + self.assertEqual(discount_for_order(order), Decimal("0")) + self.assertEqual(describe_discount(order), "none") + + def test_gold_tier_discount(self): + order = order_with([("P-105", 1)], tier="gold") + self.assertEqual(discount_for_order(order), Decimal("6.23")) + self.assertEqual(describe_discount(order), "tier 6.23") + + def test_platinum_tier_discount(self): + order = order_with([("P-102", 2)], tier="platinum") + self.assertEqual(discount_for_order(order), Decimal("4.98")) + + def test_percent_coupon_after_tier(self): + order = order_with([("P-102", 2)], tier="silver", coupon="WELCOME10") + self.assertEqual(discount_for_order(order), Decimal("6.32")) + self.assertEqual(describe_discount(order), "tier 1.49, coupon 4.83") + + def test_coupon_code_is_case_insensitive(self): + order = order_with([("P-107", 4)], coupon="welcome10") + self.assertEqual(discount_for_order(order), Decimal("5.68")) + + def test_flat_coupon_needs_minimum_subtotal(self): + order = order_with([("P-100", 2)], coupon="SAVE5") + self.assertEqual(discount_for_order(order), Decimal("0")) + + def test_flat_coupon_applies_over_minimum(self): + order = order_with([("P-107", 4)], coupon="SAVE5") + self.assertEqual(discount_for_order(order), Decimal("5.00")) + + def test_unknown_coupon_is_ignored(self): + order = order_with([("P-107", 4)], coupon="NOPE50") + self.assertEqual(discount_for_order(order), Decimal("0")) + + def test_all_discounts_combined(self): + _customers, orders, _inv = load_demo() + order = orders[0] + self.assertEqual(order.order_id, "O-1001") + self.assertEqual(discount_for_order(order), Decimal("25.57")) + self.assertEqual(describe_discount(order), "volume 2.70, tier 9.82, coupon 13.05") + + def test_bulk_coupon_with_silver_tier(self): + _customers, orders, _inv = load_demo() + order = orders[4] + self.assertEqual(describe_discount(order), "tier 5.93, coupon 20.00") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_extras.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_extras.py new file mode 100644 index 00000000..c9de45eb --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_extras.py @@ -0,0 +1,121 @@ +import unittest +from decimal import Decimal + +from helpers import customer, run_cli +from shop.analytics import ( + average_order_value, + best_customers, + orders_between, + repeat_customer_ids, + revenue_by_month, + top_products, +) +from shop.cart import Cart +from shop.export import column_sums, orders_to_csv +from shop.sample import load_demo + + +class AnalyticsTests(unittest.TestCase): + def setUp(self): + _c, self.orders, _inv = load_demo() + + def test_revenue_by_month(self): + self.assertEqual(revenue_by_month(self.orders), {"2024-03": Decimal("801.77")}) + + def test_orders_between_mixed_date_styles(self): + picked = orders_between(self.orders, "2024-03-05", "08.03.2024") + self.assertEqual([o.order_id for o in picked], ["O-1002", "O-1003", "O-1004", "O-1005"]) + + def test_orders_between_empty_window(self): + self.assertEqual(orders_between(self.orders, "2025-01-01", "2025-01-31"), []) + + def test_top_products(self): + self.assertEqual(top_products(self.orders), [("P-101", 20), ("P-100", 14), ("P-103", 4)]) + self.assertEqual(len(top_products(self.orders, 5)), 5) + + def test_average_order_value(self): + self.assertEqual(average_order_value(self.orders), Decimal("100.22")) + self.assertEqual(average_order_value([]), Decimal("0.00")) + + def test_best_customers_by_spend_with_tax(self): + best = best_customers(self.orders, 2) + self.assertEqual(best, [("c005", Decimal("171.57")), ("c001", Decimal("160.49"))]) + + def test_repeat_customers(self): + self.assertEqual(repeat_customer_ids(self.orders), ["c001", "c003"]) + + +class ExportTests(unittest.TestCase): + def test_csv_export(self): + _c, orders, _inv = load_demo() + lines = orders_to_csv(orders).splitlines() + self.assertEqual(lines[0], "order_id,customer,date,subtotal,discount,tax,shipping,total") + self.assertEqual(lines[1], "O-1001,c001,2024-03-04,143.00,25.57,22.31,0.00,139.74") + self.assertEqual(lines[5], "O-1005,c005,2024-03-08,197.50,25.93,0.00,0.00,171.57") + self.assertEqual(len(lines), 9) + + def test_column_sums(self): + _c, orders, _inv = load_demo() + self.assertEqual( + column_sums(orders), + { + "subtotal": Decimal("727.61"), + "discount": Decimal("70.79"), + "tax": Decimal("80.45"), + "shipping": Decimal("64.50"), + "total": Decimal("801.77"), + }, + ) + + def test_cli_export_matches_function(self): + _c, orders, _inv = load_demo() + self.assertEqual(run_cli("export"), (0, orders_to_csv(orders))) + + def test_cli_stats(self): + code, out = run_cli("stats") + self.assertEqual(code, 0) + self.assertEqual( + out.splitlines(), + ["2024-03 801.77", "average order 100.22", "top products: P-101 x20, P-100 x14, P-103 x4"], + ) + + +class CartTests(unittest.TestCase): + def test_estimate_matches_order_total(self): + cart = Cart(customer(tier="gold"), coupon="WELCOME10") + cart.add("P-100", 12) + cart.add("P-105") + self.assertEqual(cart.count(), 13) + self.assertEqual( + cart.estimate(), + { + "net": Decimal("117.43"), + "tax": Decimal("22.31"), + "shipping": Decimal("0.00"), + "total": Decimal("139.74"), + }, + ) + + def test_estimate_with_shipping(self): + cart = Cart(customer(country="US")) + cart.add("P-103") + self.assertEqual(cart.estimate()["total"], Decimal("21.98")) + + def test_remove_and_unknown_sku(self): + cart = Cart(customer()) + cart.add("P-100", 2) + self.assertTrue(cart.remove("P-100")) + self.assertFalse(cart.remove("P-100")) + with self.assertRaises(KeyError): + cart.add("P-999") + + def test_to_order_sorts_lines_by_sku(self): + cart = Cart(customer()) + cart.add("P-105") + cart.add("P-100", 3) + order = cart.to_order("C-1") + self.assertEqual([(l.product.sku, l.qty) for l in order.lines], [("P-100", 3), ("P-105", 1)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_invoices.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_invoices.py new file mode 100644 index 00000000..286cedce --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_invoices.py @@ -0,0 +1,94 @@ +import unittest +from datetime import date +from decimal import Decimal + +from helpers import order_with +from shop.invoices import build_invoice, format_invoice, invoice_number, is_overdue +from shop.sample import load_demo + + +class InvoiceTests(unittest.TestCase): + def setUp(self): + _customers, self.orders, _inv = load_demo() + + def test_number_comes_from_order_id(self): + self.assertEqual(invoice_number(self.orders[1]), "INV-01002") + self.assertEqual(invoice_number(order_with([], order_id="X-77")), "INV-00077") + + def test_amounts_with_international_shipping(self): + inv = build_invoice(self.orders[1]) + self.assertEqual(inv.subtotal, Decimal("70.77")) + self.assertEqual(inv.discount, Decimal("2.12")) + self.assertEqual(inv.tax, Decimal("13.73")) + self.assertEqual(inv.shipping, Decimal("14.50")) + self.assertEqual(inv.total, Decimal("96.88")) + + def test_amounts_with_free_shipping(self): + inv = build_invoice(self.orders[0]) + self.assertEqual( + (inv.subtotal, inv.discount, inv.tax, inv.shipping, inv.total), + (Decimal("143.00"), Decimal("25.57"), Decimal("22.31"), Decimal("0"), Decimal("139.74")), + ) + + def test_tax_exempt_customer(self): + inv = build_invoice(self.orders[4]) + self.assertEqual(inv.tax, Decimal("0")) + self.assertEqual(inv.total, Decimal("171.57")) + + def test_every_demo_invoice_total(self): + totals = [str(build_invoice(o).total) for o in self.orders] + self.assertEqual( + totals, + ["139.74", "96.88", "132.68", "96.54", "171.57", "105.50", "27.25", "31.61"], + ) + + def test_dates(self): + inv = build_invoice(self.orders[1]) + self.assertEqual((inv.issued, inv.due), ("2024-03-05", "2024-03-19")) + later = build_invoice(self.orders[1], issued=date(2024, 12, 20)) + self.assertEqual((later.issued, later.due), ("2024-12-20", "2025-01-03")) + + def test_order_without_date_is_rejected(self): + order = order_with([("P-100", 1)], placed_on=None) + with self.assertRaises(ValueError): + build_invoice(order) + + def test_rows(self): + inv = build_invoice(self.orders[0]) + self.assertEqual(inv.rows, [("P-100", 12, Decimal("54.00")), ("P-105", 1, Decimal("89.00"))]) + + def test_formatted_invoice(self): + text = format_invoice(build_invoice(self.orders[0])) + self.assertEqual( + text.splitlines(), + [ + "Invoice INV-01001 for Anna Becker", + " P-100 x12 54.00", + " P-105 x1 89.00", + " subtotal 143.00", + " discount -25.57", + " tax 22.31", + " shipping 0.00", + " TOTAL 139.74 EUR, due 2024-03-18", + ], + ) + + def test_no_discount_line_without_discount(self): + text = format_invoice(build_invoice(self.orders[7])) + self.assertNotIn("discount", text) + + def test_overdue_accepts_several_date_styles(self): + inv = build_invoice(self.orders[0]) + self.assertEqual(inv.due, "2024-03-18") + self.assertFalse(is_overdue(inv, "2024-03-18")) + self.assertTrue(is_overdue(inv, "2024-03-19")) + self.assertTrue(is_overdue(inv, "2024/03/20")) + + def test_overdue_rejects_garbage(self): + inv = build_invoice(self.orders[0]) + with self.assertRaises(ValueError): + is_overdue(inv, "yesterday") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_orders_customers.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_orders_customers.py new file mode 100644 index 00000000..0d44488d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_orders_customers.py @@ -0,0 +1,123 @@ +import unittest +from datetime import date + +from helpers import customer, order_with +from shop.customers import ( + Cust, + customers_by_tier, + find_customer, + is_valid_email, + load_customers, + suggest_tier, + years_as_customer, +) +from shop.orders import add_line, new_order, order_summary, order_weight, remove_line +from shop.products import find_products, get_product, price_of, search_products +from shop.sample import CUSTOMERS_CSV, load_demo +from decimal import Decimal + + +class CustomerTests(unittest.TestCase): + def test_load_customers(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual(len(customers), 6) + first = customers[0] + self.assertIsInstance(first, Cust) + self.assertEqual((first.cid, first.name, first.tier, first.country), ("c001", "Anna Becker", "gold", "DE")) + self.assertEqual(first.joined, date(2019, 3, 14)) + self.assertFalse(first.tax_exempt) + + def test_exempt_flag(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual([c.cid for c in customers if c.tax_exempt], ["c005"]) + + def test_blank_lines_and_comments_are_skipped(self): + text = "\n# comment\n\nc9, Zed, z@example.org, , AT, 2022-12-31, 0\n" + customers = load_customers(text) + self.assertEqual(len(customers), 1) + self.assertEqual(customers[0].tier, "bronze") + + def test_bad_join_date_is_rejected(self): + with self.assertRaises(ValueError): + load_customers("c9, Zed, z@example.org, gold, AT, 2022-13-40, 0") + + def test_find_customer(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual(find_customer(customers, "c004").name, "Mira Novak") + self.assertIsNone(find_customer(customers, "c999")) + + def test_group_by_tier(self): + groups = customers_by_tier(load_customers(CUSTOMERS_CSV)) + self.assertEqual(sorted(groups), ["bronze", "gold", "platinum", "silver"]) + self.assertEqual(len(groups["silver"]), 2) + + def test_years_as_customer(self): + c = Cust("c1", "A", "a@example.org", joined=date(2020, 6, 15)) + self.assertEqual(years_as_customer(c, date(2024, 6, 14)), 3) + self.assertEqual(years_as_customer(c, date(2024, 6, 15)), 4) + self.assertEqual(years_as_customer(Cust("c2", "B", "b@example.org"), date(2024, 1, 1)), 0) + + def test_email_validation(self): + self.assertTrue(is_valid_email("a@example.org")) + self.assertFalse(is_valid_email("a@@example.org")) + self.assertFalse(is_valid_email("@example.org")) + self.assertFalse(is_valid_email("a@example.")) + + def test_suggest_tier(self): + self.assertEqual(suggest_tier(Decimal("499.99")), "bronze") + self.assertEqual(suggest_tier(Decimal("500")), "silver") + self.assertEqual(suggest_tier(Decimal("2500")), "gold") + self.assertEqual(suggest_tier(Decimal("9000")), "platinum") + + +class ProductTests(unittest.TestCase): + def test_lookup(self): + self.assertEqual(get_product("P-105").name, "Mechanical keyboard") + self.assertEqual(price_of("P-100"), Decimal("4.50")) + with self.assertRaises(KeyError): + get_product("P-999") + + def test_find_by_category_skips_inactive(self): + self.assertEqual([p.sku for p in find_products("office")], ["P-110"]) + self.assertEqual(len(find_products("electronics")), 3) + + def test_search(self): + self.assertEqual([p.sku for p in search_products("PENS")], ["P-101"]) + self.assertEqual(search_products("fax"), []) + + +class OrderTests(unittest.TestCase): + def test_country_defaults_to_customer_country(self): + order = new_order("T-9", customer(country="FR")) + self.assertEqual(order.ship_country, "FR") + self.assertEqual(order.lines, []) + + def test_adding_same_sku_merges_lines(self): + order = order_with([("P-100", 2)]) + add_line(order, get_product("P-100"), 3) + self.assertEqual(len(order.lines), 1) + self.assertEqual(order.lines[0].qty, 5) + + def test_quantity_must_be_positive(self): + order = order_with([]) + with self.assertRaises(ValueError): + add_line(order, get_product("P-100"), 0) + + def test_remove_line(self): + order = order_with([("P-100", 2), ("P-101", 1)]) + self.assertTrue(remove_line(order, "P-100")) + self.assertFalse(remove_line(order, "P-100")) + self.assertEqual([l.product.sku for l in order.lines], ["P-101"]) + + def test_weight(self): + order = order_with([("P-106", 2), ("P-100", 1)]) + self.assertEqual(order_weight(order), Decimal("5.90")) + + def test_summary_text(self): + _customers, orders, _inv = load_demo() + self.assertEqual(order_summary(orders[0]), "Order O-1001: 2 lines, total 139.74 EUR") + self.assertEqual(order_summary(orders[6]), "Order O-1007: 1 lines, total 27.25 EUR") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_reports_cli.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_reports_cli.py new file mode 100644 index 00000000..86af6c6e --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_reports_cli.py @@ -0,0 +1,175 @@ +import unittest + +from helpers import render, run_cli +from shop import reports +from shop.invoices import build_invoice +from shop.inventory import Inventory +from shop.products import default_catalog +from shop.sample import STOCK, load_demo + +SALES = [ + 'SALES REPORT', + '========================================', + 'O-1001 Anna Becker 139.74', + 'O-1002 Luc Martin 96.88', + 'O-1003 Joe Smith 132.68', + 'O-1004 Mira Novak 96.54', + 'O-1005 Acme GmbH 171.57', + 'O-1006 Sven Berg 105.50', + 'O-1007 Anna Becker 27.25', + 'O-1008 Joe Smith 31.61', + '----------------------------------------', + 'TOTAL 801.77', + '8 orders', + ] + +CUSTOMERS = [ + 'CUSTOMER REPORT', + '========================================', + 'c001 Anna Becker gold 2 orders 160.49', + 'c002 Luc Martin silver 1 orders 82.38', + 'c003 Joe Smith bronze 2 orders 149.79', + 'c004 Mira Novak platinum 1 orders 82.04', + 'c005 Acme GmbH silver 1 orders 171.57', + 'c006 Sven Berg bronze 1 orders 91.00', + ] + +INVENTORY = [ + 'INVENTORY REPORT', + '========================================', + 'P-100 Notebook A5 40', + 'P-101 Ballpoint pens (10) 100', + 'P-102 Desk lamp 8', + 'P-103 USB cable 1m 60', + 'P-104 Wireless mouse 3 LOW', + 'P-105 Mechanical keyboard 6', + 'P-106 Monitor stand 12', + 'P-107 Coffee beans 1kg 25', + 'P-108 Tea sampler 4 LOW', + 'P-109 Office chair 2 LOW', + 'P-110 Whiteboard 90x60 7', + 'P-111 E-book bundle 999', + 'P-112 Fax paper roll 0', + 'stock value 15,066.95', + ] + +TAX = [ + 'TAX SUMMARY', + '========================================', + 'CZ net 68.94 tax 13.10 (19.0%)', + 'DE net 306.44 tax 25.62 (8.4%)', + 'FR net 68.65 tax 13.73 (20.0%)', + 'SE net 72.80 tax 18.20 (25.0%)', + 'US net 139.99 tax 9.80 (7.0%)', + 'ALL net 656.82 tax 80.45', + ] + +AGING = [ + 'AGING REPORT as of 2024-04-10', + '========================================', + 'INV-01001 2024-03-18 139.74 1-30 days', + 'INV-01002 2024-03-19 96.88 1-30 days', + 'INV-01003 2024-03-20 132.68 1-30 days', + 'INV-01004 2024-03-21 96.54 1-30 days', + 'INV-01005 2024-03-22 171.57 1-30 days', + 'INV-01006 2024-03-25 105.50 1-30 days', + 'INV-01007 2024-03-26 27.25 1-30 days', + 'INV-01008 2024-03-29 31.61 1-30 days', + ] + + +class ReportTests(unittest.TestCase): + def setUp(self): + self.customers, self.orders, self.inv = load_demo() + + def test_sales_report(self): + self.assertEqual(render(reports.sales_report, self.orders).splitlines(), SALES) + + def test_customer_report(self): + text = render(reports.customer_report, self.customers, self.orders) + self.assertEqual(text.splitlines(), CUSTOMERS) + + def test_inventory_report(self): + text = render(reports.inventory_report, self.inv, default_catalog()) + self.assertEqual(text.splitlines(), INVENTORY) + + def test_tax_summary(self): + self.assertEqual(render(reports.tax_summary, self.orders).splitlines(), TAX) + + def test_aging_report(self): + invoices = [build_invoice(o) for o in self.orders] + text = render(reports.aging_report, invoices, "2024-04-10") + self.assertEqual(text.splitlines(), AGING) + + def test_aging_buckets(self): + invoices = [build_invoice(o) for o in self.orders[:2]] + early = render(reports.aging_report, invoices, "2024-03-10").splitlines() + self.assertEqual([l.split()[-1] for l in early[2:]], ["current", "current"]) + late = render(reports.aging_report, invoices, "Jun 1, 2024").splitlines() + self.assertEqual([" ".join(l.split()[3:]) for l in late[2:]], ["over 30 days", "over 30 days"]) + + def test_aging_with_unreadable_date(self): + invoices = [build_invoice(o) for o in self.orders[:1]] + text = render(reports.aging_report, invoices, "someday") + self.assertTrue(text.splitlines()[2].endswith("n/a")) + + def test_aging_accepts_day_first_dates(self): + invoices = [build_invoice(o) for o in self.orders[:1]] + text = render(reports.aging_report, invoices, "10/04/2024") + self.assertTrue(text.splitlines()[2].endswith("1-30 days")) + + def test_empty_inventory_report(self): + text = render(reports.inventory_report, Inventory(), default_catalog()[:1]) + self.assertEqual(text.splitlines()[-1], "stock value 0.00") + self.assertEqual(Inventory(STOCK).available("P-111"), 999) + + +class CliTests(unittest.TestCase): + def test_sales_report_output(self): + code, out = run_cli("report", "sales") + self.assertEqual(code, 0) + self.assertEqual(out.splitlines(), SALES) + self.assertTrue(out.endswith("\n")) + self.assertFalse(out.endswith("\n\n")) + + def test_other_reports(self): + self.assertEqual(run_cli("report", "customers")[1].splitlines(), CUSTOMERS) + self.assertEqual(run_cli("report", "inventory")[1].splitlines(), INVENTORY) + self.assertEqual(run_cli("report", "tax")[1].splitlines(), TAX) + + def test_aging_report_output(self): + code, out = run_cli("report", "aging", "2024-04-10") + self.assertEqual(code, 0) + self.assertEqual(out.splitlines(), AGING) + + def test_invoice_command(self): + code, out = run_cli("invoice", "O-1002") + self.assertEqual(code, 0) + self.assertEqual(out.splitlines()[0], "Invoice INV-01002 for Luc Martin") + self.assertEqual(out.splitlines()[-1], " TOTAL 96.88 EUR, due 2024-03-19") + + def test_points_command(self): + self.assertEqual(run_cli("points", "O-1001"), (0, "O-1001 earns 176 points (worth 1.76 EUR)\n")) + + def test_quote_command(self): + code, out = run_cli("quote", "O-1005") + self.assertEqual(out, "Order O-1005: 2 lines, total 171.57 EUR\ndiscount: tier 5.93, coupon 20.00\n") + + def test_confirm_command(self): + code, out = run_cli("confirm", "O-1003") + self.assertEqual(code, 0) + self.assertIn("Total: 132.68 EUR", out) + + def test_errors_do_not_print_to_stdout(self): + self.assertEqual(run_cli("invoice", "O-9999"), (1, "")) + self.assertEqual(run_cli("report", "weather"), (2, "")) + self.assertEqual(run_cli("frobnicate"), (2, "")) + + def test_help(self): + code, out = run_cli() + self.assertEqual(code, 0) + self.assertIn("usage: python -m shop.cli", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_services.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_services.py new file mode 100644 index 00000000..40781ea2 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_services.py @@ -0,0 +1,189 @@ +import unittest +from datetime import date +from decimal import Decimal + +from helpers import order_with +from shop.currency import fmt_money, fmt_pct, money +from shop.customers import load_customers +from shop.inventory import Inventory, OutOfStock, low_stock, reserve_order +from shop.loyalty import points_for_order, redeem_value +from shop.notifications import low_stock_alert, order_confirmation +from shop.returns import can_return, refund_amount +from shop.sample import CUSTOMERS_CSV, STOCK, load_demo +from shop.storage import dump_orders, parse_orders +from shop.validation import ValidationError, ensure_valid, validate_order + + +class CurrencyTests(unittest.TestCase): + def test_money_rounds_half_up(self): + self.assertEqual(money("2.675"), Decimal("2.68")) + self.assertEqual(money(Decimal("0.005")), Decimal("0.01")) + + def test_formatting(self): + self.assertEqual(fmt_money(Decimal("1234567.5")), "1,234,567.50") + self.assertEqual(fmt_pct(Decimal("0.195")), "19.5%") + + +class InventoryTests(unittest.TestCase): + def test_reserve_and_release(self): + inv = Inventory({"P-100": 10}) + inv.reserve("P-100", 4) + self.assertEqual(inv.available("P-100"), 6) + inv.release("P-100", 10) + self.assertEqual(inv.available("P-100"), 10) + + def test_cannot_reserve_more_than_available(self): + inv = Inventory({"P-100": 3}) + with self.assertRaises(OutOfStock): + inv.reserve("P-100", 4) + self.assertEqual(inv.available("P-100"), 3) + + def test_ship_reduces_stock(self): + inv = Inventory({"P-100": 5}) + inv.reserve("P-100", 2) + inv.ship("P-100", 2) + self.assertEqual((inv.stock["P-100"], inv.available("P-100")), (3, 3)) + + def test_low_stock_default_threshold(self): + _c, _o, inv = load_demo() + self.assertEqual(low_stock(inv), ["P-104", "P-108", "P-109"]) + + def test_low_stock_custom_threshold(self): + inv = Inventory(STOCK) + self.assertEqual(low_stock(inv, 3), ["P-104", "P-109"]) + self.assertEqual(low_stock(inv, 0), []) + + def test_reserve_order_is_all_or_nothing(self): + inv = Inventory({"P-100": 5, "P-101": 1}) + order = order_with([("P-100", 2), ("P-101", 2)]) + with self.assertRaises(OutOfStock): + reserve_order(inv, order) + self.assertEqual(inv.available("P-100"), 5) + reserve_order(inv, order_with([("P-100", 2), ("P-101", 1)])) + self.assertEqual(inv.available("P-100"), 3) + + +class LoyaltyTests(unittest.TestCase): + def test_points_follow_tier(self): + _c, orders, _inv = load_demo() + self.assertEqual([points_for_order(o) for o in orders[:3]], [176, 85, 124]) + + def test_points_are_truncated(self): + _c, orders, _inv = load_demo() + self.assertEqual(points_for_order(orders[4]), 214) + + def test_redeem_value(self): + self.assertEqual(redeem_value(176), Decimal("1.76")) + self.assertEqual(redeem_value(0), Decimal("0.00")) + + +class ReturnTests(unittest.TestCase): + def setUp(self): + _c, self.orders, _inv = load_demo() + + def test_window_is_thirty_days(self): + order = self.orders[0] + self.assertTrue(can_return(order, date(2024, 4, 3))) + self.assertFalse(can_return(order, date(2024, 4, 4))) + + def test_cancelled_and_undated_orders_cannot_be_returned(self): + order = order_with([("P-100", 1)], placed_on=None) + self.assertFalse(can_return(order, date(2024, 3, 2))) + dated = order_with([("P-100", 1)]) + dated.status = "cancelled" + self.assertFalse(can_return(dated, date(2024, 3, 2))) + + def test_refund_single_line_order(self): + self.assertEqual(refund_amount(self.orders[6], "P-104", 1), Decimal("18.67")) + + def test_refund_share_of_multi_line_order(self): + self.assertEqual(refund_amount(self.orders[0], "P-100", 6), Decimal("23.74")) + self.assertEqual(refund_amount(self.orders[0], "P-105", 1), Decimal("78.27")) + + def test_refund_errors(self): + with self.assertRaises(KeyError): + refund_amount(self.orders[0], "P-999", 1) + with self.assertRaises(ValueError): + refund_amount(self.orders[0], "P-105", 2) + + +class StorageTests(unittest.TestCase): + def test_parse_demo_orders(self): + _c, orders, _inv = load_demo() + self.assertEqual(len(orders), 8) + self.assertEqual(orders[0].placed_on, date(2024, 3, 4)) + self.assertEqual(orders[1].placed_on, date(2024, 3, 5)) + self.assertEqual([len(o.lines) for o in orders], [2, 2, 1, 2, 2, 2, 1, 2]) + + def test_dump_and_parse_round_trip(self): + customers, orders, _inv = load_demo() + text = dump_orders(orders) + self.assertEqual(text.splitlines()[0], "O-1001;c001;P-100:12,P-105:1;WELCOME10;DE;2024-03-04") + again = parse_orders(text, customers) + self.assertEqual(again, orders) + + def test_unknown_customer(self): + customers = load_customers(CUSTOMERS_CSV) + with self.assertRaises(KeyError): + parse_orders("O-1; c999; P-100:1; ; DE; 2024-03-01", customers) + + def test_bad_order_date(self): + customers = load_customers(CUSTOMERS_CSV) + with self.assertRaises(ValueError): + parse_orders("O-1; c001; P-100:1; ; DE; 31.02.2024", customers) + + def test_both_date_styles(self): + customers = load_customers(CUSTOMERS_CSV) + orders = parse_orders("O-1; c001; P-100:1; ; DE; 3.4.2024\nO-2; c001; P-100:1; ; DE; 2024-04-03", customers) + self.assertEqual(orders[0].placed_on, orders[1].placed_on) + + +class ValidationTests(unittest.TestCase): + def test_valid_order(self): + self.assertEqual(validate_order(order_with([("P-100", 2)])), []) + + def test_empty_order(self): + self.assertEqual(validate_order(order_with([])), ["order has no lines"]) + + def test_quantity_limit(self): + problems = validate_order(order_with([("P-100", 101)])) + self.assertEqual(problems, ["P-100: quantity 101 exceeds 100"]) + self.assertEqual(validate_order(order_with([("P-100", 100)])), []) + + def test_inactive_product_and_country(self): + problems = validate_order(order_with([("P-112", 1)], country="BR")) + self.assertEqual(problems, ["P-112: product is not active", "unknown country: BR"]) + + def test_malformed_coupon(self): + problems = validate_order(order_with([("P-100", 1)], coupon="10-OFF")) + self.assertEqual(problems, ["malformed coupon: 10-OFF"]) + + def test_ensure_valid_raises(self): + with self.assertRaises(ValidationError): + ensure_valid(order_with([])) + ensure_valid(order_with([("P-100", 1)])) + + +class NotificationTests(unittest.TestCase): + def test_confirmation_text(self): + _c, orders, _inv = load_demo() + text = order_confirmation(orders[2]) + self.assertEqual( + text.splitlines(), + [ + "Dear Joe Smith,", + "", + "thank you for your order O-1003.", + " 1x Office chair", + "Total: 132.68 EUR", + "Coupon applied: SAVE5", + ], + ) + + def test_low_stock_alert(self): + self.assertEqual(low_stock_alert([]), "") + self.assertEqual(low_stock_alert(["P-104", "P-109"]), "Low stock: Wireless mouse, Office chair") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_tax_shipping.py b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_tax_shipping.py new file mode 100644 index 00000000..c7bbb973 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/hidden/tests/test_tax_shipping.py @@ -0,0 +1,89 @@ +import unittest +from decimal import Decimal + +from helpers import customer, order_with +from shop.sample import load_demo +from shop.shipping import is_free_shipping, shipping_cost +from shop.tax import rate_for, tax_breakdown, tax_for_order + + +class TaxTests(unittest.TestCase): + def test_default_rate(self): + self.assertEqual(rate_for("DE"), Decimal("0.19")) + self.assertEqual(rate_for("BR"), Decimal("0.19")) + + def test_regional_rates(self): + self.assertEqual(rate_for("FR"), Decimal("0.20")) + self.assertEqual(rate_for("US"), Decimal("0.07")) + self.assertEqual(rate_for("CH"), Decimal("0.081")) + + def test_exempt_customer_pays_no_tax(self): + self.assertEqual(rate_for("FR", customer(exempt=True)), Decimal("0")) + self.assertEqual(rate_for("FR", customer()), Decimal("0.20")) + + def test_tax_for_plain_order(self): + self.assertEqual(tax_for_order(order_with([("P-105", 1)])), Decimal("16.91")) + + def test_tax_is_rounded_half_up(self): + order = order_with([("P-105", 1)], country="CH") + self.assertEqual(tax_for_order(order), Decimal("7.21")) + + def test_tax_is_on_discounted_net(self): + _customers, orders, _inv = load_demo() + self.assertEqual(tax_for_order(orders[0]), Decimal("22.31")) + + def test_exempt_order_has_zero_tax(self): + order = order_with([("P-105", 1)], exempt=True) + self.assertEqual(tax_for_order(order), Decimal("0.00")) + + def test_breakdown_per_country(self): + _customers, orders, _inv = load_demo() + self.assertEqual( + tax_breakdown(orders), + { + "DE": Decimal("25.62"), + "FR": Decimal("13.73"), + "US": Decimal("9.80"), + "CZ": Decimal("13.10"), + "SE": Decimal("18.20"), + }, + ) + + +class ShippingTests(unittest.TestCase): + def test_home_country_flat_rate(self): + self.assertEqual(shipping_cost(order_with([("P-103", 1)])), Decimal("6.50")) + + def test_international_surcharge(self): + self.assertEqual(shipping_cost(order_with([("P-103", 1)], country="FR")), Decimal("14.50")) + self.assertEqual(shipping_cost(order_with([("P-103", 1)], country="US")), Decimal("14.50")) + + def test_heavy_parcel_adds_per_kg_fee(self): + order = order_with([("P-106", 2)]) + self.assertEqual(shipping_cost(order), Decimal("7.22")) + + def test_free_shipping_over_threshold(self): + order = order_with([("P-105", 2)]) + self.assertTrue(is_free_shipping(order)) + self.assertEqual(shipping_cost(order), Decimal("0.00")) + + def test_threshold_is_inclusive(self): + order = order_with([("P-101", 5), ("P-111", 7)]) + self.assertTrue(is_free_shipping(order)) + + def test_just_below_threshold_pays(self): + order = order_with([("P-101", 4), ("P-111", 7)]) + self.assertFalse(is_free_shipping(order)) + self.assertEqual(shipping_cost(order), Decimal("6.50")) + + def test_free_shipping_uses_discounted_amount(self): + items = [("P-105", 1), ("P-103", 2)] + self.assertEqual(shipping_cost(order_with(items)), Decimal("0.00")) + self.assertEqual(shipping_cost(order_with(items, tier="gold")), Decimal("6.50")) + + def test_empty_order_ships_nothing(self): + self.assertEqual(shipping_cost(order_with([])), Decimal("0.00")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/docs/ARCHITECTURE.md b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/docs/ARCHITECTURE.md new file mode 100644 index 00000000..982141b3 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/docs/ARCHITECTURE.md @@ -0,0 +1,51 @@ +# Architecture + +The shop is a small order-processing library with a command line front end. +Everything lives in the `shop/` package and uses only the standard library. +Money is always `decimal.Decimal`, rounded half-up to cents by `currency.money`. + +## Core modules + +* `config.py` defines the frozen `Config` dataclass and `DEFAULT_CONFIG`. Every + rate, threshold and limit of the shop (tax rates, shipping fees, discount + rules, loyalty, returns, validation limits) is a field of `Config`; no other + module defines such constants. Functions that depend on them take an optional + `config` keyword argument. +* `pricing.py` contains `price_order(order, config)`, the only place where a + subtotal, discount, tax, shipping cost and total are computed. It returns a + frozen `PriceBreakdown`. `discounts.py`, `tax.py` and `shipping.py` are thin + wrappers around it that keep the old per-topic entry points. +* `dates.py` contains `parse_date`, the single parser for all date formats the + shop reads (ISO, slash, dotted day-first and `Mon D, YYYY`). + +## Data model + +* `customers.py` defines the `Customer` dataclass (id, name, e-mail, tier, + country, join date, tax-exempt flag) and the CSV loader `load_customers`. +* `products.py` holds the immutable `Product` and the built-in catalog. +* `orders.py` defines `Order` and `OrderLine` and the helpers to build them + (`new_order`, `add_line`, `remove_line`). +* `inventory.py` tracks stock and reservations. +* `storage.py` reads and writes the order text format. + +## Services + +* `invoices.py`: invoice records built from `price_order`, text formatting and + the overdue check. +* `loyalty.py`, `returns.py`, `validation.py`, `notifications.py`: points, + refunds, order checks and customer messages. +* `cart.py`, `analytics.py`, `export.py`: quote basket, revenue statistics and CSV + export; all of them price orders through `pricing.py`. +* `util.py`: small string helpers. + +## Reports and command line + +The functions in `reports.py` (`sales_report`, `customer_report`, +`inventory_report`, `tax_summary`, `aging_report`) build and return a string and +never print. `cli.py` dispatches the sub commands of `python -m shop.cli` and is +the only module that writes to stdout; `sample.py` provides the demo data set. + +## Tests + +`python3 -m unittest discover -s tests` runs the whole suite. The tests pin the +numbers of the demo data, so any change to the pricing rules shows up there. diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/analytics.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/analytics.py new file mode 100644 index 00000000..66669234 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/analytics.py @@ -0,0 +1,60 @@ +from collections import Counter +from decimal import Decimal + +from .config import resolve +from .currency import money +from .dates import parse_date +from .pricing import price_order + + +def month_key(order): + if order.placed_on is None: + return "unknown" + return "%04d-%02d" % (order.placed_on.year, order.placed_on.month) + + +def revenue_by_month(orders, config=None): + cfg = resolve(config) + result = {} + for o in orders: + key = month_key(o) + result[key] = result.get(key, Decimal("0")) + price_order(o, cfg).total + return result + + +def orders_between(orders, start_text, end_text): + """Orders placed from start to end, both ends included.""" + start = parse_date(start_text) + end = parse_date(end_text) + return [o for o in orders if o.placed_on is not None and start <= o.placed_on <= end] + + +def top_products(orders, n=3): + counts = Counter() + for o in orders: + for line in o.lines: + counts[line.product.sku] += line.qty + ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])) + return ranked[:n] + + +def average_order_value(orders, config=None): + cfg = resolve(config) + if not orders: + return Decimal("0.00") + return money(sum((price_order(o, cfg).total for o in orders), Decimal("0")) / len(orders)) + + +def best_customers(orders, n=3, config=None): + cfg = resolve(config) + spend = {} + for o in orders: + price = price_order(o, cfg) + spend[o.customer.cid] = spend.get(o.customer.cid, Decimal("0")) + price.subtotal - price.discount + price.tax + ranked = sorted(spend.items(), key=lambda kv: (-kv[1], kv[0])) + return ranked[:n] + + +def repeat_customer_ids(orders): + seen = Counter(o.customer.cid for o in orders) + return sorted(cid for cid, n in seen.items() if n > 1) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cart.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cart.py new file mode 100644 index 00000000..78163c36 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cart.py @@ -0,0 +1,45 @@ +from .config import resolve +from .orders import add_line, new_order +from .pricing import price_order +from .products import get_product + + +class Cart: + """A basket that is not an order yet; used by the quote screen.""" + + def __init__(self, customer, country=None, coupon=None): + self.customer = customer + self.country = country or customer.country + self.coupon = coupon + self.items = {} + + def add(self, sku, qty=1): + get_product(sku) + self.items[sku] = self.items.get(sku, 0) + qty + + def remove(self, sku): + return self.items.pop(sku, None) is not None + + def count(self): + return sum(self.items.values()) + + def to_order(self, order_id, placed_on=None): + order = new_order( + order_id, + self.customer, + coupon=self.coupon, + ship_country=self.country, + placed_on=placed_on, + ) + for sku in sorted(self.items): + add_line(order, get_product(sku), self.items[sku]) + return order + + def estimate(self, config=None): + price = price_order(self.to_order("CART"), resolve(config)) + return { + "net": price.subtotal - price.discount, + "tax": price.tax, + "shipping": price.shipping, + "total": price.total, + } diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cli.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cli.py new file mode 100644 index 00000000..a8e7e4d8 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/cli.py @@ -0,0 +1,89 @@ +import sys + +from . import reports +from .analytics import average_order_value, revenue_by_month, top_products +from .currency import fmt_money +from .discounts import describe_discount +from .export import orders_to_csv +from .invoices import build_invoice, format_invoice +from .loyalty import points_for_order, redeem_value +from .notifications import order_confirmation +from .orders import order_summary +from .products import default_catalog +from .sample import load_demo + +USAGE = """usage: python -m shop.cli COMMAND [ARGS] + +commands: + report sales|customers|inventory|tax + report aging TODAY + invoice ORDER_ID + points ORDER_ID + quote ORDER_ID + confirm ORDER_ID + stats + export +""" + + +def _find(orders, order_id): + for o in orders: + if o.order_id == order_id: + return o + return None + + +def main(argv=None): + args = list(sys.argv[1:] if argv is None else argv) + if not args or args[0] in ("-h", "--help"): + print(USAGE) + return 0 + customers, orders, inv = load_demo() + cmd = args[0] + if cmd == "report" and len(args) >= 2: + which = args[1] + if which == "sales": + print(reports.sales_report(orders)) + elif which == "customers": + print(reports.customer_report(customers, orders)) + elif which == "inventory": + print(reports.inventory_report(inv, default_catalog())) + elif which == "tax": + print(reports.tax_summary(orders)) + elif which == "aging" and len(args) >= 3: + print(reports.aging_report([build_invoice(o) for o in orders], args[2])) + else: + print("unknown report: %s" % which, file=sys.stderr) + return 2 + return 0 + if cmd == "stats" and len(args) == 1: + for month, total in sorted(revenue_by_month(orders).items()): + print("%s %s" % (month, fmt_money(total))) + print("average order %s" % fmt_money(average_order_value(orders))) + print("top products: " + ", ".join("%s x%d" % (sku, n) for sku, n in top_products(orders))) + return 0 + if cmd == "export" and len(args) == 1: + sys.stdout.write(orders_to_csv(orders)) + return 0 + if cmd in ("invoice", "points", "quote", "confirm") and len(args) == 2: + order = _find(orders, args[1]) + if order is None: + print("no such order: %s" % args[1], file=sys.stderr) + return 1 + if cmd == "invoice": + print(format_invoice(build_invoice(order))) + elif cmd == "points": + pts = points_for_order(order) + print("%s earns %d points (worth %s EUR)" % (order.order_id, pts, redeem_value(pts))) + elif cmd == "quote": + print(order_summary(order)) + print("discount: %s" % describe_discount(order)) + else: + print(order_confirmation(order)) + return 0 + print(USAGE, file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/config.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/config.py new file mode 100644 index 00000000..fbbefbd1 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/config.py @@ -0,0 +1,60 @@ +"""Business parameters of the shop: rates, thresholds and limits in one place.""" + +from dataclasses import dataclass, field +from decimal import Decimal +from typing import Dict, Optional + + +def _rates(**values: str) -> Dict[str, Decimal]: + return {key: Decimal(value) for key, value in values.items()} + + +@dataclass(frozen=True) +class Config: + """Immutable set of pricing rules and limits; use dataclasses.replace to vary it.""" + + home_country: str = "DE" + default_tax_rate: Decimal = Decimal("0.19") + region_tax_rates: Dict[str, Decimal] = field( + default_factory=lambda: _rates(FR="0.20", US="0.07", CH="0.081", SE="0.25") + ) + free_shipping_threshold: Decimal = Decimal("100.00") + shipping_flat: Decimal = Decimal("6.50") + free_weight_kg: Decimal = Decimal("5") + shipping_per_kg: Decimal = Decimal("1.20") + international_surcharge: Decimal = Decimal("8.00") + volume_min_qty: int = 10 + volume_rate: Decimal = Decimal("0.05") + tier_rates: Dict[str, Decimal] = field( + default_factory=lambda: _rates(bronze="0", silver="0.03", gold="0.07", platinum="0.10") + ) + coupon_percent: Dict[str, Decimal] = field( + default_factory=lambda: _rates(WELCOME10="0.10", SPRING15="0.15") + ) + coupon_flat: Dict[str, Decimal] = field( + default_factory=lambda: _rates(SAVE5="5.00", BULK20="20.00") + ) + coupon_flat_min_subtotal: Decimal = Decimal("50.00") + tier_spend_thresholds: Dict[str, Decimal] = field( + default_factory=lambda: _rates(silver="500", gold="2000", platinum="5000") + ) + loyalty_points_per_unit: int = 1 + loyalty_multipliers: Dict[str, Decimal] = field( + default_factory=lambda: _rates(bronze="1", silver="1.25", gold="1.5", platinum="2") + ) + loyalty_point_value: Decimal = Decimal("0.01") + low_stock_threshold: int = 5 + invoice_due_days: int = 14 + return_window_days: int = 30 + restocking_fee_rate: Decimal = Decimal("0.10") + max_line_qty: int = 100 + max_order_lines: int = 25 + aging_bucket_days: int = 30 + + +DEFAULT_CONFIG = Config() + + +def resolve(config: Optional[Config]) -> Config: + """Return the given config, or DEFAULT_CONFIG when it is None.""" + return DEFAULT_CONFIG if config is None else config diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/customers.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/customers.py new file mode 100644 index 00000000..db9d0cd7 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/customers.py @@ -0,0 +1,79 @@ +from dataclasses import dataclass +from datetime import date +from typing import Optional + +from .config import resolve +from .dates import parse_date + +TIER_ORDER = ["bronze", "silver", "gold", "platinum"] + + +@dataclass +class Customer: + cid: str + name: str + email: str + tier: str = "bronze" + country: str = "DE" + joined: Optional[date] = None + tax_exempt: bool = False + + +def load_customers(text): + result = [] + for raw in text.strip().splitlines(): + raw = raw.strip() + if not raw or raw.startswith("#"): + continue + cid, name, email, tier, country, joined, exempt = [f.strip() for f in raw.split(",")] + result.append( + Customer( + cid, + name, + email, + tier or "bronze", + country, + parse_date(joined) if joined else None, + exempt == "1", + ) + ) + return result + + +def find_customer(customers, cid): + for c in customers: + if c.cid == cid: + return c + return None + + +def customers_by_tier(customers): + groups = {} + for c in customers: + groups.setdefault(c.tier, []).append(c) + return groups + + +def years_as_customer(cust, today): + if cust.joined is None: + return 0 + years = today.year - cust.joined.year + if (today.month, today.day) < (cust.joined.month, cust.joined.day): + years -= 1 + return max(years, 0) + + +def is_valid_email(addr): + if addr.count("@") != 1: + return False + local, domain = addr.split("@") + return bool(local) and "." in domain and not domain.startswith(".") and not domain.endswith(".") + + +def suggest_tier(total_spend, config=None): + thresholds = resolve(config).tier_spend_thresholds + best = "bronze" + for tier in TIER_ORDER[1:]: + if total_spend >= thresholds[tier]: + best = tier + return best diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/dates.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/dates.py new file mode 100644 index 00000000..677d001e --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/dates.py @@ -0,0 +1,25 @@ +"""The single date parser for every text format the shop reads.""" + +import re +from datetime import date + +_MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec") +_YEAR_FIRST = re.compile(r"^(\d{4})([-/])(\d{1,2})\2(\d{1,2})$") +_DAY_FIRST = re.compile(r"^(\d{1,2})([./])(\d{1,2})\2(\d{4})$") +_NAMED = re.compile(r"^([A-Za-z]{3,9}) (\d{1,2}), (\d{4})$") + + +def parse_date(text: str) -> date: + """Parse YYYY-MM-DD, YYYY/MM/DD, D.M.YYYY, D/M/YYYY or 'Mon D, YYYY'; raise ValueError otherwise.""" + value = text.strip() + m = _YEAR_FIRST.match(value) + if m: + return date(int(m.group(1)), int(m.group(3)), int(m.group(4))) + m = _DAY_FIRST.match(value) + if m: + return date(int(m.group(4)), int(m.group(3)), int(m.group(1))) + m = _NAMED.match(value) + if m and m.group(1)[:3].lower() in _MONTHS: + month = _MONTHS.index(m.group(1)[:3].lower()) + 1 + return date(int(m.group(3)), month, int(m.group(2))) + raise ValueError("unrecognised date: %r" % text) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/discounts.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/discounts.py new file mode 100644 index 00000000..cb47a9a3 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/discounts.py @@ -0,0 +1,19 @@ +from .config import resolve +from .currency import fmt_money +from .pricing import discount_parts, price_order + + +def discount_for_order(order, config=None): + return price_order(order, resolve(config)).discount + + +def describe_discount(order, config=None): + volume, tier, coupon = discount_parts(order, resolve(config)) + parts = [] + if volume: + parts.append("volume %s" % fmt_money(volume)) + if tier: + parts.append("tier %s" % fmt_money(tier)) + if coupon: + parts.append("coupon %s" % fmt_money(coupon)) + return ", ".join(parts) if parts else "none" diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/export.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/export.py new file mode 100644 index 00000000..ee09b9d7 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/export.py @@ -0,0 +1,35 @@ +from .config import resolve +from .currency import money +from .pricing import price_order + +CSV_HEADER = ("order_id", "customer", "date", "subtotal", "discount", "tax", "shipping", "total") + + +def order_row(order, config=None): + price = price_order(order, resolve(config)) + when = order.placed_on.isoformat() if order.placed_on else "" + return [ + order.order_id, + order.customer.cid, + when, + str(money(price.subtotal)), + str(money(price.discount)), + str(money(price.tax)), + str(money(price.shipping)), + str(money(price.total)), + ] + + +def orders_to_csv(orders, config=None): + rows = [",".join(CSV_HEADER)] + for order in orders: + rows.append(",".join(order_row(order, config))) + return "\n".join(rows) + "\n" + + +def column_sums(orders): + sums = [money(0)] * 5 + for order in orders: + for i, cell in enumerate(order_row(order)[3:]): + sums[i] = sums[i] + money(cell) + return dict(zip(CSV_HEADER[3:], sums)) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/inventory.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/inventory.py new file mode 100644 index 00000000..8b4c2439 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/inventory.py @@ -0,0 +1,49 @@ +from .config import resolve + + +class OutOfStock(Exception): + pass + + +class Inventory: + def __init__(self, stock=None): + self.stock = dict(stock or {}) + self.reserved = {} + + def available(self, sku): + return self.stock.get(sku, 0) - self.reserved.get(sku, 0) + + def restock(self, sku, qty): + self.stock[sku] = self.stock.get(sku, 0) + qty + + def reserve(self, sku, qty): + if qty > self.available(sku): + raise OutOfStock("%s: wanted %d, have %d" % (sku, qty, self.available(sku))) + self.reserved[sku] = self.reserved.get(sku, 0) + qty + + def release(self, sku, qty): + have = self.reserved.get(sku, 0) + self.reserved[sku] = max(have - qty, 0) + + def ship(self, sku, qty): + self.stock[sku] = self.stock.get(sku, 0) - qty + self.release(sku, qty) + + +def low_stock(inv, threshold=None, config=None): + if threshold is None: + threshold = resolve(config).low_stock_threshold + return sorted(sku for sku in inv.stock if inv.available(sku) <= threshold) + + +def reserve_order(inv, order): + done = [] + try: + for line in order.lines: + inv.reserve(line.product.sku, line.qty) + done.append(line) + except OutOfStock: + for line in done: + inv.release(line.product.sku, line.qty) + raise + diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/invoices.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/invoices.py new file mode 100644 index 00000000..66856a19 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/invoices.py @@ -0,0 +1,70 @@ +from dataclasses import dataclass +from datetime import timedelta +from decimal import Decimal +from typing import List, Tuple + +from .config import resolve +from .currency import fmt_money +from .dates import parse_date +from .pricing import price_order + + +@dataclass +class Invoice: + number: str + order_id: str + customer_name: str + rows: List[Tuple[str, int, Decimal]] + subtotal: Decimal + discount: Decimal + tax: Decimal + shipping: Decimal + total: Decimal + issued: str + due: str + + +def invoice_number(order): + digits = "".join(ch for ch in order.order_id if ch.isdigit()) + return "INV-" + digits.zfill(5) + + +def build_invoice(order, issued=None, config=None): + cfg = resolve(config) + if issued is None: + issued = order.placed_on + if issued is None: + raise ValueError("order %s has no date" % order.order_id) + price = price_order(order, cfg) + rows = [(ln.product.sku, ln.qty, ln.product.price * ln.qty) for ln in order.lines] + due = issued + timedelta(days=cfg.invoice_due_days) + return Invoice( + number=invoice_number(order), + order_id=order.order_id, + customer_name=order.customer.name, + rows=rows, + subtotal=price.subtotal, + discount=price.discount, + tax=price.tax, + shipping=price.shipping, + total=price.total, + issued=issued.isoformat(), + due=due.isoformat(), + ) + + +def format_invoice(inv): + out = ["Invoice %s for %s" % (inv.number, inv.customer_name)] + for sku, qty, amount in inv.rows: + out.append(" %-6s x%-3d %10s" % (sku, qty, fmt_money(amount))) + out.append(" subtotal %s" % fmt_money(inv.subtotal)) + if inv.discount: + out.append(" discount -%s" % fmt_money(inv.discount)) + out.append(" tax %s" % fmt_money(inv.tax)) + out.append(" shipping %s" % fmt_money(inv.shipping)) + out.append(" TOTAL %s EUR, due %s" % (fmt_money(inv.total), inv.due)) + return "\n".join(out) + + +def is_overdue(inv, today_text): + return parse_date(today_text) > parse_date(inv.due) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/loyalty.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/loyalty.py new file mode 100644 index 00000000..263d7832 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/loyalty.py @@ -0,0 +1,16 @@ +from .config import resolve +from .currency import money +from .pricing import price_order + + +def points_for_order(order, config=None): + """Whole points earned on the net total of an order.""" + cfg = resolve(config) + price = price_order(order, cfg) + net = price.subtotal - price.discount + mult = cfg.loyalty_multipliers.get(order.customer.tier, 1) + return int(net * cfg.loyalty_points_per_unit * mult) + + +def redeem_value(points, config=None): + return money(points * resolve(config).loyalty_point_value) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/notifications.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/notifications.py new file mode 100644 index 00000000..1a095a35 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/notifications.py @@ -0,0 +1,23 @@ +from .config import resolve +from .currency import fmt_money +from .pricing import price_order +from .products import get_product +from .util import join_nonempty + + +def order_confirmation(order, config=None): + total = price_order(order, resolve(config)).total + lines = ["Dear %s," % order.customer.name, "", "thank you for your order %s." % order.order_id] + for line in order.lines: + lines.append(" %dx %s" % (line.qty, line.product.name)) + lines.append("Total: %s EUR" % fmt_money(total)) + if order.coupon: + lines.append("Coupon applied: %s" % order.coupon.upper()) + return "\n".join(lines) + + +def low_stock_alert(skus): + if not skus: + return "" + names = [get_product(s).name for s in skus] + return join_nonempty(["Low stock", ", ".join(names)], sep=": ") diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/orders.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/orders.py new file mode 100644 index 00000000..42af7fde --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/orders.py @@ -0,0 +1,70 @@ +from dataclasses import dataclass, field +from datetime import date +from decimal import Decimal +from typing import List, Optional + +from .config import resolve +from .currency import fmt_money +from .customers import Customer +from .pricing import price_order +from .products import Product + + +@dataclass +class OrderLine: + product: Product + qty: int + + +@dataclass +class Order: + order_id: str + customer: Customer + lines: List[OrderLine] = field(default_factory=list) + coupon: Optional[str] = None + ship_country: str = "DE" + placed_on: Optional[date] = None + status: str = "new" + + +def new_order(order_id, customer, coupon=None, ship_country=None, placed_on=None): + return Order( + order_id=order_id, + customer=customer, + coupon=coupon, + ship_country=ship_country or customer.country, + placed_on=placed_on, + ) + + +def add_line(order, product, qty): + if qty <= 0: + raise ValueError("quantity must be positive") + for line in order.lines: + if line.product.sku == product.sku: + line.qty += qty + return line + line = OrderLine(product, qty) + order.lines.append(line) + return line + + +def remove_line(order, sku): + before = len(order.lines) + order.lines = [l for l in order.lines if l.product.sku != sku] + return len(order.lines) != before + + +def order_weight(order): + kg = Decimal("0") + for line in order.lines: + kg += line.product.weight_kg * line.qty + return kg + + +def order_summary(order, config=None): + return "Order %s: %d lines, total %s EUR" % ( + order.order_id, + len(order.lines), + fmt_money(price_order(order, resolve(config)).total), + ) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/pricing.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/pricing.py new file mode 100644 index 00000000..ad593b30 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/pricing.py @@ -0,0 +1,83 @@ +"""Order pricing: the one place where subtotal, discount, tax, shipping and total are computed.""" + +from dataclasses import dataclass +from decimal import Decimal +from typing import TYPE_CHECKING, Optional, Tuple + +from .config import DEFAULT_CONFIG, Config, resolve +from .currency import money + +if TYPE_CHECKING: + from .orders import Order + + +@dataclass(frozen=True) +class PriceBreakdown: + """The amounts of a priced order, rounded to cents.""" + + subtotal: Decimal + discount: Decimal + tax: Decimal + shipping: Decimal + total: Decimal + + +def tax_rate_for(country: str, tax_exempt: bool, config: Optional[Config] = None) -> Decimal: + """Tax rate for a shipping country; tax-exempt customers pay none.""" + cfg = resolve(config) + if tax_exempt: + return Decimal("0") + return cfg.region_tax_rates.get(country, cfg.default_tax_rate) + + +def _subtotal(order: "Order") -> Decimal: + return sum((line.product.price * line.qty for line in order.lines), Decimal("0")) + + +def discount_parts(order: "Order", config: Optional[Config] = None) -> Tuple[Decimal, Decimal, Decimal]: + """Volume, tier and coupon discount of an order, applied in that order.""" + cfg = resolve(config) + subtotal = _subtotal(order) + volume = Decimal("0") + for line in order.lines: + if line.qty >= cfg.volume_min_qty: + volume += money(line.product.price * line.qty * cfg.volume_rate) + after_volume = subtotal - volume + tier = money(after_volume * cfg.tier_rates.get(order.customer.tier, Decimal("0"))) + base = after_volume - tier + code = (order.coupon or "").upper() + coupon = Decimal("0") + if code in cfg.coupon_percent: + coupon = money(base * cfg.coupon_percent[code]) + elif code in cfg.coupon_flat and subtotal >= cfg.coupon_flat_min_subtotal: + coupon = min(cfg.coupon_flat[code], base) + return volume, tier, coupon + + +def _shipping(order: "Order", net: Decimal, cfg: Config) -> Decimal: + if not order.lines or net >= cfg.free_shipping_threshold: + return Decimal("0") + cost = cfg.shipping_flat + weight = sum((line.product.weight_kg * line.qty for line in order.lines), Decimal("0")) + if weight > cfg.free_weight_kg: + cost += money((weight - cfg.free_weight_kg) * cfg.shipping_per_kg) + if order.ship_country != cfg.home_country: + cost += cfg.international_surcharge + return cost + + +def price_order(order: "Order", config: Optional[Config] = DEFAULT_CONFIG) -> PriceBreakdown: + """Price an order with the given rules (DEFAULT_CONFIG when config is None).""" + cfg = resolve(config) + subtotal = _subtotal(order) + discount = sum(discount_parts(order, cfg), Decimal("0")) + net = subtotal - discount + tax = money(net * tax_rate_for(order.ship_country, order.customer.tax_exempt, cfg)) + shipping = _shipping(order, net, cfg) + return PriceBreakdown( + subtotal=money(subtotal), + discount=money(discount), + tax=tax, + shipping=money(shipping), + total=money(net + tax + shipping), + ) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/products.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/products.py new file mode 100644 index 00000000..6d7f6e73 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/products.py @@ -0,0 +1,57 @@ +from dataclasses import dataclass +from decimal import Decimal + + +@dataclass(frozen=True) +class Product: + sku: str + name: str + price: Decimal + weight_kg: Decimal + category: str = "general" + active: bool = True + + +def default_catalog(): + return [ + Product("P-100", "Notebook A5", Decimal("4.50"), Decimal("0.30"), "stationery"), + Product("P-101", "Ballpoint pens (10)", Decimal("3.20"), Decimal("0.10"), "stationery"), + Product("P-102", "Desk lamp", Decimal("24.90"), Decimal("1.20"), "home"), + Product("P-103", "USB cable 1m", Decimal("6.99"), Decimal("0.08"), "electronics"), + Product("P-104", "Wireless mouse", Decimal("18.75"), Decimal("0.12"), "electronics"), + Product("P-105", "Mechanical keyboard", Decimal("89.00"), Decimal("1.10"), "electronics"), + Product("P-106", "Monitor stand", Decimal("35.00"), Decimal("2.80"), "home"), + Product("P-107", "Coffee beans 1kg", Decimal("14.20"), Decimal("1.05"), "food"), + Product("P-108", "Tea sampler", Decimal("9.90"), Decimal("0.40"), "food"), + Product("P-109", "Office chair", Decimal("129.00"), Decimal("9.50"), "furniture"), + Product("P-110", "Whiteboard 90x60", Decimal("42.50"), Decimal("3.90"), "office"), + Product("P-111", "E-book bundle", Decimal("12.00"), Decimal("0"), "digital"), + Product("P-112", "Fax paper roll", Decimal("2.10"), Decimal("0.25"), "office", active=False), + ] + + +_by_sku = {} + + +def get_product(sku): + if not _by_sku: + for p in default_catalog(): + _by_sku[p.sku] = p + try: + return _by_sku[sku] + except KeyError: + raise KeyError("unknown sku: %s" % sku) + + +def price_of(sku): + return get_product(sku).price + + +def find_products(category): + return [p for p in default_catalog() if p.category == category and p.active] + + +def search_products(term): + term = term.lower() + return [p for p in default_catalog() if term in p.name.lower() and p.active] + diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/reports.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/reports.py new file mode 100644 index 00000000..8f36264f --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/reports.py @@ -0,0 +1,107 @@ +from decimal import Decimal + +from .config import resolve +from .currency import fmt_money, fmt_pct +from .customers import suggest_tier +from .dates import parse_date +from .inventory import low_stock +from .pricing import price_order +from .util import truncate + + +def _try_parse(text): + try: + return parse_date(text or "") + except ValueError: + return None + + +def sales_report(orders, config=None): + cfg = resolve(config) + lines = ["SALES REPORT", "=" * 40] + grand = Decimal("0") + for o in sorted(orders, key=lambda o: o.order_id): + total = price_order(o, cfg).total + grand += total + lines.append("%-8s %-16s %12s" % (o.order_id, truncate(o.customer.name, 16), fmt_money(total))) + lines.append("-" * 40) + lines.append("%-25s %12s" % ("TOTAL", fmt_money(grand))) + lines.append("%d orders" % len(orders)) + return "\n".join(lines) + + +def customer_report(customers, orders, config=None): + cfg = resolve(config) + lines = ["CUSTOMER REPORT", "=" * 40] + for c in sorted(customers, key=lambda c: c.cid): + mine = [o for o in orders if o.customer.cid == c.cid] + prices = [price_order(o, cfg) for o in mine] + spend = sum((p.subtotal - p.discount + p.tax for p in prices), Decimal("0")) + line = "%-5s %-14s %-9s %2d orders %10s" % ( + c.cid, + truncate(c.name, 14), + c.tier, + len(mine), + fmt_money(spend), + ) + better = suggest_tier(spend, config=cfg) + if better != c.tier and better != "bronze": + line += " suggest %s" % better + lines.append(line) + return "\n".join(lines) + + +def inventory_report(inv, catalog, config=None): + cfg = resolve(config) + lines = ["INVENTORY REPORT", "=" * 40] + low = set(low_stock(inv, config=cfg)) + value = Decimal("0") + for p in sorted(catalog, key=lambda p: p.sku): + have = inv.available(p.sku) + value += p.price * max(have, 0) + flag = " LOW" if p.sku in low else "" + lines.append("%-6s %-22s %5d%s" % (p.sku, truncate(p.name, 22), have, flag)) + lines.append("stock value %s" % fmt_money(value)) + return "\n".join(lines) + + +def tax_summary(orders, config=None): + cfg = resolve(config) + lines = ["TAX SUMMARY", "=" * 40] + all_net = Decimal("0") + all_tax = Decimal("0") + for cc in sorted(set(o.ship_country for o in orders)): + net = Decimal("0") + tax = Decimal("0") + for o in orders: + if o.ship_country == cc: + price = price_order(o, cfg) + net += price.subtotal - price.discount + tax += price.tax + rate = tax / net if net else Decimal("0") + lines.append("%-3s net %10s tax %9s (%s)" % (cc, fmt_money(net), fmt_money(tax), fmt_pct(rate))) + all_net += net + all_tax += tax + lines.append("ALL net %10s tax %9s" % (fmt_money(all_net), fmt_money(all_tax))) + return "\n".join(lines) + + +def aging_report(invoices, today_text, config=None): + cfg = resolve(config) + days = cfg.aging_bucket_days + lines = ["AGING REPORT as of %s" % today_text, "=" * 40] + today = _try_parse(today_text) + for inv in sorted(invoices, key=lambda i: i.number): + due = _try_parse(inv.due) + if due is None or today is None: + bucket = "n/a" + else: + late = (today - due).days + if late <= 0: + bucket = "current" + elif late <= days: + bucket = "1-%d days" % days + else: + bucket = "over %d days" % days + lines.append("%-10s %-12s %10s %s" % (inv.number, inv.due, fmt_money(inv.total), bucket)) + return "\n".join(lines) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/returns.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/returns.py new file mode 100644 index 00000000..252e83cb --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/returns.py @@ -0,0 +1,27 @@ +from .config import resolve +from .currency import money +from .pricing import price_order + + +def can_return(order, today, config=None): + if order.placed_on is None or order.status == "cancelled": + return False + return (today - order.placed_on).days <= resolve(config).return_window_days + + +def refund_amount(order, sku, qty, config=None): + """Refund for returning qty units of sku: its share of net + tax, minus the restocking fee.""" + cfg = resolve(config) + line = None + for candidate in order.lines: + if candidate.product.sku == sku: + line = candidate + if line is None: + raise KeyError("order %s has no line %s" % (order.order_id, sku)) + if qty <= 0 or qty > line.qty: + raise ValueError("cannot return %d of %d" % (qty, line.qty)) + price = price_order(order, cfg) + share = (line.product.price * qty) / price.subtotal + base = (price.subtotal - price.discount + price.tax) * share + fee = money(base * cfg.restocking_fee_rate) + return money(base) - fee diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/shipping.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/shipping.py new file mode 100644 index 00000000..6684241d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/shipping.py @@ -0,0 +1,18 @@ +from decimal import Decimal + +from .config import resolve +from .pricing import price_order + + +def parcel_weight(order): + return sum((line.product.weight_kg * line.qty for line in order.lines), Decimal("0")) + + +def is_free_shipping(order, config=None): + cfg = resolve(config) + price = price_order(order, cfg) + return price.subtotal - price.discount >= cfg.free_shipping_threshold + + +def shipping_cost(order, config=None): + return price_order(order, resolve(config)).shipping diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/storage.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/storage.py new file mode 100644 index 00000000..f193cec7 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/storage.py @@ -0,0 +1,38 @@ +from .customers import find_customer +from .dates import parse_date +from .orders import add_line, new_order +from .products import get_product + + +def parse_orders(text, customers): + """Parse lines of ``order;customer;sku:qty,sku:qty;coupon;country;date``.""" + orders = [] + for raw in text.strip().splitlines(): + raw = raw.strip() + if not raw or raw.startswith("#"): + continue + order_id, cid, items, coupon, country, when = [f.strip() for f in raw.split(";")] + cust = find_customer(customers, cid) + if cust is None: + raise KeyError("unknown customer: %s" % cid) + order = new_order( + order_id, + cust, + coupon=coupon or None, + ship_country=country or None, + placed_on=parse_date(when) if when else None, + ) + for item in items.split(","): + sku, qty = item.split(":") + add_line(order, get_product(sku.strip()), int(qty)) + orders.append(order) + return orders + + +def dump_orders(orders): + rows = [] + for o in orders: + items = ",".join("%s:%d" % (l.product.sku, l.qty) for l in o.lines) + when = o.placed_on.isoformat() if o.placed_on else "" + rows.append(";".join([o.order_id, o.customer.cid, items, o.coupon or "", o.ship_country, when])) + return "\n".join(rows) + "\n" diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/tax.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/tax.py new file mode 100644 index 00000000..b2fc4d13 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/tax.py @@ -0,0 +1,22 @@ +from decimal import Decimal + +from .config import resolve +from .pricing import price_order, tax_rate_for + + +def rate_for(country, customer=None, config=None): + exempt = customer is not None and customer.tax_exempt + return tax_rate_for(country, exempt, resolve(config)) + + +def tax_for_order(order, config=None): + return price_order(order, resolve(config)).tax + + +def tax_breakdown(orders, config=None): + """Tax collected per shipping country.""" + cfg = resolve(config) + result = {} + for order in orders: + result[order.ship_country] = result.get(order.ship_country, Decimal("0")) + tax_for_order(order, cfg) + return result diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/util.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/util.py new file mode 100644 index 00000000..274147cf --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/util.py @@ -0,0 +1,8 @@ +def truncate(text, width): + if len(text) <= width: + return text + return text[: width - 1] + "~" + + +def join_nonempty(parts, sep=", "): + return sep.join(p for p in parts if p) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/validation.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/validation.py new file mode 100644 index 00000000..87b06e86 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/shop/validation.py @@ -0,0 +1,35 @@ +import re + +from .config import resolve + +KNOWN_COUNTRIES = ("DE", "FR", "US", "CZ", "SE", "CH", "AT", "NL") + + +class ValidationError(ValueError): + pass + + +def validate_order(order, config=None): + """Return a list of problems; an empty list means the order is fine.""" + cfg = resolve(config) + problems = [] + if not order.lines: + problems.append("order has no lines") + if len(order.lines) > cfg.max_order_lines: + problems.append("too many lines: %d" % len(order.lines)) + for line in order.lines: + if line.qty > cfg.max_line_qty: + problems.append("%s: quantity %d exceeds %d" % (line.product.sku, line.qty, cfg.max_line_qty)) + if not line.product.active: + problems.append("%s: product is not active" % line.product.sku) + if order.ship_country not in KNOWN_COUNTRIES: + problems.append("unknown country: %s" % order.ship_country) + if order.coupon and not re.match(r"^[A-Z]+[0-9]+$", order.coupon.upper()): + problems.append("malformed coupon: %s" % order.coupon) + return problems + + +def ensure_valid(order): + problems = validate_order(order) + if problems: + raise ValidationError("; ".join(problems)) diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/helpers.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/helpers.py new file mode 100644 index 00000000..8176cb50 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/helpers.py @@ -0,0 +1,42 @@ +import contextlib +import io +from datetime import date + +from shop.cli import main +from shop.customers import Customer +from shop.orders import add_line, new_order +from shop.products import get_product + + +def customer(cid="c900", tier="bronze", country="DE", exempt=False): + return Customer(cid, "Test " + cid, cid + "@example.org", tier, country, date(2020, 1, 1), exempt) + + +def order_with(items, tier="bronze", country="DE", coupon=None, exempt=False, order_id="T-1", placed_on=date(2024, 3, 1)): + order = new_order( + order_id, + customer(tier=tier, country=country, exempt=exempt), + coupon=coupon, + ship_country=country, + placed_on=placed_on, + ) + for sku, qty in items: + add_line(order, get_product(sku), qty) + return order + + +def run_cli(*argv): + """Run the command line tool, return (exit code, stdout).""" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(list(argv)) + return code, buf.getvalue() + + +def render(fn, *args, **kwargs): + """Text produced by a report function, whether it returns it or prints it.""" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + result = fn(*args, **kwargs) + text = result if isinstance(result, str) else buf.getvalue() + return text.rstrip("\n") diff --git a/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/test_orders_customers.py b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/test_orders_customers.py new file mode 100644 index 00000000..4b02d8cb --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/reference/overlay/tests/test_orders_customers.py @@ -0,0 +1,123 @@ +import unittest +from datetime import date + +from helpers import customer, order_with +from shop.customers import ( + Customer, + customers_by_tier, + find_customer, + is_valid_email, + load_customers, + suggest_tier, + years_as_customer, +) +from shop.orders import add_line, new_order, order_summary, order_weight, remove_line +from shop.products import find_products, get_product, price_of, search_products +from shop.sample import CUSTOMERS_CSV, load_demo +from decimal import Decimal + + +class CustomerTests(unittest.TestCase): + def test_load_customers(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual(len(customers), 6) + first = customers[0] + self.assertIsInstance(first, Customer) + self.assertEqual((first.cid, first.name, first.tier, first.country), ("c001", "Anna Becker", "gold", "DE")) + self.assertEqual(first.joined, date(2019, 3, 14)) + self.assertFalse(first.tax_exempt) + + def test_exempt_flag(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual([c.cid for c in customers if c.tax_exempt], ["c005"]) + + def test_blank_lines_and_comments_are_skipped(self): + text = "\n# comment\n\nc9, Zed, z@example.org, , AT, 2022-12-31, 0\n" + customers = load_customers(text) + self.assertEqual(len(customers), 1) + self.assertEqual(customers[0].tier, "bronze") + + def test_bad_join_date_is_rejected(self): + with self.assertRaises(ValueError): + load_customers("c9, Zed, z@example.org, gold, AT, 2022-13-40, 0") + + def test_find_customer(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual(find_customer(customers, "c004").name, "Mira Novak") + self.assertIsNone(find_customer(customers, "c999")) + + def test_group_by_tier(self): + groups = customers_by_tier(load_customers(CUSTOMERS_CSV)) + self.assertEqual(sorted(groups), ["bronze", "gold", "platinum", "silver"]) + self.assertEqual(len(groups["silver"]), 2) + + def test_years_as_customer(self): + c = Customer("c1", "A", "a@example.org", joined=date(2020, 6, 15)) + self.assertEqual(years_as_customer(c, date(2024, 6, 14)), 3) + self.assertEqual(years_as_customer(c, date(2024, 6, 15)), 4) + self.assertEqual(years_as_customer(Customer("c2", "B", "b@example.org"), date(2024, 1, 1)), 0) + + def test_email_validation(self): + self.assertTrue(is_valid_email("a@example.org")) + self.assertFalse(is_valid_email("a@@example.org")) + self.assertFalse(is_valid_email("@example.org")) + self.assertFalse(is_valid_email("a@example.")) + + def test_suggest_tier(self): + self.assertEqual(suggest_tier(Decimal("499.99")), "bronze") + self.assertEqual(suggest_tier(Decimal("500")), "silver") + self.assertEqual(suggest_tier(Decimal("2500")), "gold") + self.assertEqual(suggest_tier(Decimal("9000")), "platinum") + + +class ProductTests(unittest.TestCase): + def test_lookup(self): + self.assertEqual(get_product("P-105").name, "Mechanical keyboard") + self.assertEqual(price_of("P-100"), Decimal("4.50")) + with self.assertRaises(KeyError): + get_product("P-999") + + def test_find_by_category_skips_inactive(self): + self.assertEqual([p.sku for p in find_products("office")], ["P-110"]) + self.assertEqual(len(find_products("electronics")), 3) + + def test_search(self): + self.assertEqual([p.sku for p in search_products("PENS")], ["P-101"]) + self.assertEqual(search_products("fax"), []) + + +class OrderTests(unittest.TestCase): + def test_country_defaults_to_customer_country(self): + order = new_order("T-9", customer(country="FR")) + self.assertEqual(order.ship_country, "FR") + self.assertEqual(order.lines, []) + + def test_adding_same_sku_merges_lines(self): + order = order_with([("P-100", 2)]) + add_line(order, get_product("P-100"), 3) + self.assertEqual(len(order.lines), 1) + self.assertEqual(order.lines[0].qty, 5) + + def test_quantity_must_be_positive(self): + order = order_with([]) + with self.assertRaises(ValueError): + add_line(order, get_product("P-100"), 0) + + def test_remove_line(self): + order = order_with([("P-100", 2), ("P-101", 1)]) + self.assertTrue(remove_line(order, "P-100")) + self.assertFalse(remove_line(order, "P-100")) + self.assertEqual([l.product.sku for l in order.lines], ["P-101"]) + + def test_weight(self): + order = order_with([("P-106", 2), ("P-100", 1)]) + self.assertEqual(order_weight(order), Decimal("5.90")) + + def test_summary_text(self): + _customers, orders, _inv = load_demo() + self.assertEqual(order_summary(orders[0]), "Order O-1001: 2 lines, total 139.74 EUR") + self.assertEqual(order_summary(orders[6]), "Order O-1007: 1 lines, total 27.25 EUR") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/REFACTOR.md b/scripts/e2e/codex/tasks/refactor-shop/seed/REFACTOR.md new file mode 100644 index 00000000..1038c28f --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/REFACTOR.md @@ -0,0 +1,157 @@ +# Refactoring plan + +The shop code works and is covered by tests (`python3 -m unittest discover -s tests`), +but the price calculation is copied into several modules, rates and thresholds are +scattered over the code base, and there are four different date parsers. This file +describes the cleanup. Do the steps in order; after each one the test suite must still pass. + +## Ground rules + +* Behaviour does not change. Every number, every report line and all CLI output stay + exactly as they are today. The existing tests are the reference. +* Only the standard library. +* The public functions listed under "Public API" keep their names and their positional + arguments. Functions that depend on a rate or threshold get one extra keyword argument + `config=None` (see step 2); `None` means `DEFAULT_CONFIG`. +* Remove imports that become unused. + +## Steps + +### 1. One pricing function: `shop/pricing.py` + +Create `shop/pricing.py` with + +```python +price_order(order, config=DEFAULT_CONFIG) -> PriceBreakdown +``` + +`PriceBreakdown` is a frozen dataclass with the `Decimal` fields `subtotal`, `discount`, +`tax`, `shipping`, `total`. It reproduces today's rules exactly (volume discount, tier +discount, coupon, tax with the exempt flag and the per-country rates, shipping with the +free-shipping threshold, weight fee and international surcharge), including the rounding. + +Delete the duplicated calculations `orders.calc_total`, `discounts.compute_order_total`, +`tax.order_total_with_tax` and the inline calculation in `invoices.build_invoice`. +Every module that used to compute an order total (invoices, reports, loyalty, returns, +cart, analytics, export, notifications, shipping, tax, discounts) takes its numbers from +`price_order` and keeps no arithmetic for subtotal, discount, tax or shipping of its own. +`discounts.discount_for_order`, `tax.tax_for_order`, `shipping.shipping_cost` and friends +stay as thin wrappers. + +### 2. One configuration object: `shop/config.py` + +Create `shop/config.py` with a frozen dataclass `Config` and `DEFAULT_CONFIG = Config()`. +Fields and defaults (mapping fields use `field(default_factory=...)`): + +| field | default | +| --- | --- | +| `home_country` | `"DE"` | +| `default_tax_rate` | `Decimal("0.19")` | +| `region_tax_rates` | `{"FR": 0.20, "US": 0.07, "CH": 0.081, "SE": 0.25}` as Decimal | +| `free_shipping_threshold` | `Decimal("100.00")` | +| `shipping_flat` | `Decimal("6.50")` | +| `free_weight_kg` | `Decimal("5")` | +| `shipping_per_kg` | `Decimal("1.20")` | +| `international_surcharge` | `Decimal("8.00")` | +| `volume_min_qty` | `10` | +| `volume_rate` | `Decimal("0.05")` | +| `tier_rates` | `{"bronze": 0, "silver": 0.03, "gold": 0.07, "platinum": 0.10}` as Decimal | +| `coupon_percent` | `{"WELCOME10": 0.10, "SPRING15": 0.15}` as Decimal | +| `coupon_flat` | `{"SAVE5": 5.00, "BULK20": 20.00}` as Decimal | +| `coupon_flat_min_subtotal` | `Decimal("50.00")` | +| `tier_spend_thresholds` | `{"silver": 500, "gold": 2000, "platinum": 5000}` as Decimal | +| `loyalty_points_per_unit` | `1` | +| `loyalty_multipliers` | `{"bronze": 1, "silver": 1.25, "gold": 1.5, "platinum": 2}` as Decimal | +| `loyalty_point_value` | `Decimal("0.01")` | +| `low_stock_threshold` | `5` | +| `invoice_due_days` | `14` | +| `return_window_days` | `30` | +| `restocking_fee_rate` | `Decimal("0.10")` | +| `max_line_qty` | `100` | +| `max_order_lines` | `25` | +| `aging_bucket_days` | `30` | + +No module other than `shop/config.py` may define a module-level UPPER_CASE name whose value +contains a number (an int, a float or a `Decimal(...)`). Constants made of strings only +(`USAGE`, `CSV_HEADER`, `KNOWN_COUNTRIES`, ...) may stay, and the demo data in `shop/sample.py` +is exempt. + +Every public function that depends on one of these values accepts a keyword argument `config`: + +* discounts: `discount_for_order(order, config=None)`, `describe_discount(order, config=None)` +* tax: `rate_for(country, customer=None, config=None)`, `tax_for_order(order, config=None)`, + `tax_breakdown(orders, config=None)` +* shipping: `shipping_cost(order, config=None)`, `is_free_shipping(order, config=None)` +* invoices: `build_invoice(order, issued=None, config=None)` +* reports: `sales_report(orders, config=None)`, `customer_report(customers, orders, config=None)`, + `inventory_report(inv, catalog, config=None)`, `tax_summary(orders, config=None)`, + `aging_report(invoices, today_text, config=None)` +* loyalty: `points_for_order(order, config=None)`, `redeem_value(points, config=None)` +* returns: `can_return(order, today, config=None)`, `refund_amount(order, sku, qty, config=None)` +* inventory: `low_stock(inv, threshold=None, config=None)` (an explicit `threshold` still wins) +* validation: `validate_order(order, config=None)` +* customers: `suggest_tier(total_spend, config=None)` +* notifications: `order_confirmation(order, config=None)` +* orders: `order_summary(order, config=None)` +* cart: `Cart.estimate(self, config=None)` +* analytics: `revenue_by_month(orders, config=None)`, `average_order_value(orders, config=None)`, + `best_customers(orders, n=3, config=None)` +* export: `orders_to_csv(orders, config=None)` + +### 3. Rename `Cust` to `Customer` + +Rename the class `shop.customers.Cust` to `Customer` everywhere: code, tests and docs. +No alias named `Cust` stays behind. (Editing the tests is allowed for this rename only.) + +### 4. Reports return text + +`reports.sales_report`, `customer_report`, `inventory_report`, `tax_summary` and +`aging_report` currently print. They must build and return one `str` (lines joined with +`"\n"`, no trailing newline) and must not print anything. `shop/cli.py` does the printing; +the output of every CLI command stays byte for byte the same. + +### 5. One date parser: `shop/dates.py` + +Create `shop/dates.py` with `parse_date(text: str) -> date`. It replaces the four hand-written +parsers `customers.parse_joined`, `orders.parse_order_date`, `invoices.parse_due_date` and +`reports._to_date`, which are deleted. Surrounding whitespace is ignored; accepted formats: + +* `YYYY-MM-DD` and `YYYY/MM/DD` +* `D.M.YYYY` and `D/M/YYYY` (day first, one or two digits for day and month) +* `Mon D, YYYY` with an English month abbreviation, e.g. `Mar 5, 2024` (case does not matter) + +Anything else, and impossible dates such as `2024-02-30`, raise `ValueError`. Callers keep their +current behaviour (for example the aging report shows `n/a` for a date it cannot read). Afterwards +no module except `dates.py` parses dates by hand: no `strptime`, no `fromisoformat` and no +`date(...)` or `datetime(...)` constructor calls. + +### 6. Remove dead code + +These five functions are not used anywhere. Confirm that with grep, then delete them: +`products.legacy_price_lookup`, `inventory.dump_stock_csv`, `orders.old_order_summary`, +`shipping.estimate_zone_v1`, `util.slugify`. + +### 7. Type hints and docstrings + +Every public function (and public method) in `shop/pricing.py`, `shop/config.py` and +`shop/dates.py` gets type hints for all arguments and the return value, and a docstring. +Public classes in those modules get a docstring as well. + +### 8. Documentation + +Update `docs/ARCHITECTURE.md` so it describes the new layout: `pricing.py`, `config.py` and +`dates.py`, the thin wrappers, reports returning text and `cli.py` printing. It must no longer +mention any of the removed functions, constants or the old class name. + +## Public API that must keep working + +customers: `Customer` (was `Cust`), `load_customers`, `find_customer`, `customers_by_tier`, +`years_as_customer`, `is_valid_email`, `suggest_tier`; products: `Product`, `get_product`, +`price_of`, `find_products`, `search_products`, `default_catalog`; inventory: `Inventory`, +`OutOfStock`, `low_stock`, `reserve_order`; orders: `Order`, `OrderLine`, `new_order`, `add_line`, +`remove_line`, `order_weight`, `order_summary`; discounts, tax, shipping, invoices, reports, +loyalty, returns, validation, notifications, cart, analytics, export: every function mentioned +in step 2 plus `invoice_number`, `format_invoice`, `is_overdue`, `ensure_valid`, +`low_stock_alert`, `orders_between`, `top_products`, `repeat_customer_ids`, `column_sums`; +storage: `parse_orders`, `dump_orders`; currency: `money`, `fmt_money`, `fmt_pct`; +`shop.sample.load_demo` and `shop.cli.main`. diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/docs/ARCHITECTURE.md b/scripts/e2e/codex/tasks/refactor-shop/seed/docs/ARCHITECTURE.md new file mode 100644 index 00000000..ad47061e --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/docs/ARCHITECTURE.md @@ -0,0 +1,60 @@ +# Architecture + +The shop is a small order-processing library with a command line front end. +Everything lives in the `shop/` package and uses only the standard library. +Money is always `decimal.Decimal`, rounded half-up to cents by `currency.money`. + +## Data model + +* `customers.py` defines the `Cust` dataclass (id, name, e-mail, tier, country, + join date, tax-exempt flag), the CSV loader `load_customers` and the join date + parser `parse_joined`. +* `products.py` holds the immutable `Product` and the built-in catalog. + `legacy_price_lookup` is the old price list lookup from the spreadsheet import. +* `orders.py` defines `Order` and `OrderLine` and the helpers to build them + (`new_order`, `add_line`, `remove_line`). `parse_order_date` reads the order + dates of the import files. +* `inventory.py` tracks stock and reservations. `dump_stock_csv` writes the stock + table for the warehouse. + +## Pricing + +Pricing is spread over four modules, each with its own constants: + +* `discounts.py`: volume discount (`VOLUME_DISCOUNT_RATE`), tier discount + (`TIER_RATES`) and coupons. `compute_order_total` returns the net total. +* `tax.py`: `TAX_RATE` and the per-country `REGION_RATES`. `order_total_with_tax` + returns net plus tax. +* `shipping.py`: `FREE_SHIPPING_THRESHOLD`, flat fee, per-kg fee and the + international surcharge. `estimate_zone_v1` is the zone lookup that was used + before the surcharge existed. +* `orders.py`: `calc_total` returns the grand total (net + tax + shipping) and is + what the reports and notifications use. + +`invoices.build_invoice` repeats the whole calculation inline because it needs +every intermediate amount. `parse_due_date` reads the due dates of invoices. + +## Services + +* `loyalty.py`: points for an order (`LOYALTY_POINTS_PER_UNIT`, tier multipliers). +* `returns.py`: return window and refunds (`RETURN_WINDOW_DAYS`, + `RESTOCKING_FEE_RATE`). +* `validation.py`: order checks (`MAX_LINE_QTY`, `MAX_ORDER_LINES`). +* `notifications.py`: confirmation and low-stock messages. +* `cart.py`, `analytics.py`, `export.py`: quote basket, revenue statistics and CSV + export. They call the pricing functions above. +* `storage.py`: reads and writes the order text format. +* `util.py`: small string helpers; `slugify` is used by the old web export. + +## Reports and command line + +`reports.py` contains the printing reports (`sales_report`, `customer_report`, +`inventory_report`, `tax_summary`, `aging_report`); they write to stdout +themselves. `_to_date` parses the date argument of the aging report. +`cli.py` dispatches the sub commands of `python -m shop.cli` and `sample.py` +provides the demo data set. + +## Tests + +`python3 -m unittest discover -s tests` runs the whole suite. The tests pin the +numbers of the demo data, so any change to the pricing rules shows up there. diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/__init__.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/__init__.py new file mode 100644 index 00000000..43e1036c --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/__init__.py @@ -0,0 +1 @@ +"""Order processing for a small online shop.""" diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/analytics.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/analytics.py new file mode 100644 index 00000000..09e896d9 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/analytics.py @@ -0,0 +1,55 @@ +from collections import Counter +from decimal import Decimal + +from .currency import money +from .orders import calc_total, parse_order_date +from .tax import order_total_with_tax + + +def month_key(order): + if order.placed_on is None: + return "unknown" + return "%04d-%02d" % (order.placed_on.year, order.placed_on.month) + + +def revenue_by_month(orders): + result = {} + for o in orders: + key = month_key(o) + result[key] = result.get(key, Decimal("0")) + calc_total(o) + return result + + +def orders_between(orders, start_text, end_text): + """Orders placed from start to end, both ends included.""" + start = parse_order_date(start_text) + end = parse_order_date(end_text) + return [o for o in orders if o.placed_on is not None and start <= o.placed_on <= end] + + +def top_products(orders, n=3): + counts = Counter() + for o in orders: + for line in o.lines: + counts[line.product.sku] += line.qty + ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])) + return ranked[:n] + + +def average_order_value(orders): + if not orders: + return Decimal("0.00") + return money(sum((calc_total(o) for o in orders), Decimal("0")) / len(orders)) + + +def best_customers(orders, n=3): + spend = {} + for o in orders: + spend[o.customer.cid] = spend.get(o.customer.cid, Decimal("0")) + order_total_with_tax(o) + ranked = sorted(spend.items(), key=lambda kv: (-kv[1], kv[0])) + return ranked[:n] + + +def repeat_customer_ids(orders): + seen = Counter(o.customer.cid for o in orders) + return sorted(cid for cid, n in seen.items() if n > 1) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/cart.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/cart.py new file mode 100644 index 00000000..0863cdac --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/cart.py @@ -0,0 +1,50 @@ +from .currency import money +from .discounts import compute_order_total +from .orders import add_line, new_order +from .products import get_product +from .shipping import shipping_cost +from .tax import tax_for_order + + +class Cart: + """A basket that is not an order yet; used by the quote screen.""" + + def __init__(self, customer, country=None, coupon=None): + self.customer = customer + self.country = country or customer.country + self.coupon = coupon + self.items = {} + + def add(self, sku, qty=1): + get_product(sku) + self.items[sku] = self.items.get(sku, 0) + qty + + def remove(self, sku): + return self.items.pop(sku, None) is not None + + def count(self): + return sum(self.items.values()) + + def to_order(self, order_id, placed_on=None): + order = new_order( + order_id, + self.customer, + coupon=self.coupon, + ship_country=self.country, + placed_on=placed_on, + ) + for sku in sorted(self.items): + add_line(order, get_product(sku), self.items[sku]) + return order + + def estimate(self): + order = self.to_order("CART") + net = compute_order_total(order) + tax = tax_for_order(order) + ship = shipping_cost(order) + return { + "net": money(net), + "tax": money(tax), + "shipping": money(ship), + "total": money(net + tax + ship), + } diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/cli.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/cli.py new file mode 100644 index 00000000..74bdcfb6 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/cli.py @@ -0,0 +1,89 @@ +import sys + +from . import reports +from .analytics import average_order_value, revenue_by_month, top_products +from .currency import fmt_money +from .discounts import describe_discount +from .export import orders_to_csv +from .invoices import build_invoice, format_invoice +from .loyalty import points_for_order, redeem_value +from .notifications import order_confirmation +from .orders import order_summary +from .products import default_catalog +from .sample import load_demo + +USAGE = """usage: python -m shop.cli COMMAND [ARGS] + +commands: + report sales|customers|inventory|tax + report aging TODAY + invoice ORDER_ID + points ORDER_ID + quote ORDER_ID + confirm ORDER_ID + stats + export +""" + + +def _find(orders, order_id): + for o in orders: + if o.order_id == order_id: + return o + return None + + +def main(argv=None): + args = list(sys.argv[1:] if argv is None else argv) + if not args or args[0] in ("-h", "--help"): + print(USAGE) + return 0 + customers, orders, inv = load_demo() + cmd = args[0] + if cmd == "report" and len(args) >= 2: + which = args[1] + if which == "sales": + reports.sales_report(orders) + elif which == "customers": + reports.customer_report(customers, orders) + elif which == "inventory": + reports.inventory_report(inv, default_catalog()) + elif which == "tax": + reports.tax_summary(orders) + elif which == "aging" and len(args) >= 3: + reports.aging_report([build_invoice(o) for o in orders], args[2]) + else: + print("unknown report: %s" % which, file=sys.stderr) + return 2 + return 0 + if cmd == "stats" and len(args) == 1: + for month, total in sorted(revenue_by_month(orders).items()): + print("%s %s" % (month, fmt_money(total))) + print("average order %s" % fmt_money(average_order_value(orders))) + print("top products: " + ", ".join("%s x%d" % (sku, n) for sku, n in top_products(orders))) + return 0 + if cmd == "export" and len(args) == 1: + sys.stdout.write(orders_to_csv(orders)) + return 0 + if cmd in ("invoice", "points", "quote", "confirm") and len(args) == 2: + order = _find(orders, args[1]) + if order is None: + print("no such order: %s" % args[1], file=sys.stderr) + return 1 + if cmd == "invoice": + print(format_invoice(build_invoice(order))) + elif cmd == "points": + pts = points_for_order(order) + print("%s earns %d points (worth %s EUR)" % (order.order_id, pts, redeem_value(pts))) + elif cmd == "quote": + print(order_summary(order)) + print("discount: %s" % describe_discount(order)) + else: + print(order_confirmation(order)) + return 0 + print(USAGE, file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/currency.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/currency.py new file mode 100644 index 00000000..8103485e --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/currency.py @@ -0,0 +1,13 @@ +from decimal import ROUND_HALF_UP, Decimal + + +def money(value): + return Decimal(value).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + +def fmt_money(value): + return "{:,.2f}".format(money(value)) + + +def fmt_pct(rate): + return "{:.1f}%".format(Decimal(rate) * 100) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/customers.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/customers.py new file mode 100644 index 00000000..ced4895d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/customers.py @@ -0,0 +1,89 @@ +from dataclasses import dataclass +from datetime import date +from decimal import Decimal +from typing import Optional + +TIER_SPEND = { + "silver": Decimal("500"), + "gold": Decimal("2000"), + "platinum": Decimal("5000"), +} +TIER_ORDER = ["bronze", "silver", "gold", "platinum"] + + +@dataclass +class Cust: + cid: str + name: str + email: str + tier: str = "bronze" + country: str = "DE" + joined: Optional[date] = None + tax_exempt: bool = False + + +def parse_joined(text): + parts = text.strip().split("-") + if len(parts) != 3: + raise ValueError("bad join date: %r" % text) + y, m, d = parts + return date(int(y), int(m), int(d)) + + +def load_customers(text): + result = [] + for raw in text.strip().splitlines(): + raw = raw.strip() + if not raw or raw.startswith("#"): + continue + cid, name, email, tier, country, joined, exempt = [f.strip() for f in raw.split(",")] + result.append( + Cust( + cid, + name, + email, + tier or "bronze", + country, + parse_joined(joined) if joined else None, + exempt == "1", + ) + ) + return result + + +def find_customer(customers, cid): + for c in customers: + if c.cid == cid: + return c + return None + + +def customers_by_tier(customers): + groups = {} + for c in customers: + groups.setdefault(c.tier, []).append(c) + return groups + + +def years_as_customer(cust, today): + if cust.joined is None: + return 0 + years = today.year - cust.joined.year + if (today.month, today.day) < (cust.joined.month, cust.joined.day): + years -= 1 + return max(years, 0) + + +def is_valid_email(addr): + if addr.count("@") != 1: + return False + local, domain = addr.split("@") + return bool(local) and "." in domain and not domain.startswith(".") and not domain.endswith(".") + + +def suggest_tier(total_spend): + best = "bronze" + for tier in TIER_ORDER[1:]: + if total_spend >= TIER_SPEND[tier]: + best = tier + return best diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/discounts.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/discounts.py new file mode 100644 index 00000000..1e24dfe2 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/discounts.py @@ -0,0 +1,86 @@ +from decimal import ROUND_HALF_UP, Decimal + +from .currency import fmt_money, money + +VOLUME_DISCOUNT_MIN_QTY = 10 +VOLUME_DISCOUNT_RATE = Decimal("0.05") +TIER_RATES = { + "bronze": Decimal("0"), + "silver": Decimal("0.03"), + "gold": Decimal("0.07"), + "platinum": Decimal("0.10"), +} +COUPON_PERCENT = {"WELCOME10": Decimal("0.10"), "SPRING15": Decimal("0.15")} +COUPON_FLAT = {"SAVE5": Decimal("5.00"), "BULK20": Decimal("20.00")} +COUPON_FLAT_MIN_SUBTOTAL = Decimal("50.00") + + +def order_subtotal(order): + total = Decimal("0") + for line in order.lines: + total += line.product.price * line.qty + return total + + +def volume_discount(order): + total = Decimal("0") + for line in order.lines: + if line.qty >= VOLUME_DISCOUNT_MIN_QTY: + total += money(line.product.price * line.qty * VOLUME_DISCOUNT_RATE) + return total + + +def tier_discount(order, base): + rate = TIER_RATES.get(order.customer.tier, Decimal("0")) + return money(base * rate) + + +def coupon_discount(order, base, subtotal): + code = (order.coupon or "").upper() + if code in COUPON_PERCENT: + return money(base * COUPON_PERCENT[code]) + if code in COUPON_FLAT and subtotal >= COUPON_FLAT_MIN_SUBTOTAL: + return min(COUPON_FLAT[code], base) + return Decimal("0") + + +def discount_for_order(order): + sub = order_subtotal(order) + vol = volume_discount(order) + tier = tier_discount(order, sub - vol) + coupon = coupon_discount(order, sub - vol - tier, sub) + return vol + tier + coupon + + +def describe_discount(order): + sub = order_subtotal(order) + vol = volume_discount(order) + tier = tier_discount(order, sub - vol) + coupon = coupon_discount(order, sub - vol - tier, sub) + parts = [] + if vol: + parts.append("volume %s" % fmt_money(vol)) + if tier: + parts.append("tier %s" % fmt_money(tier)) + if coupon: + parts.append("coupon %s" % fmt_money(coupon)) + return ", ".join(parts) if parts else "none" + + +def compute_order_total(order): + """Net total: goods minus discounts, before tax and shipping.""" + sub = Decimal("0") + vol = Decimal("0") + for line in order.lines: + amount = line.product.price * line.qty + sub += amount + if line.qty >= VOLUME_DISCOUNT_MIN_QTY: + vol += (amount * VOLUME_DISCOUNT_RATE).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + after = sub - vol + after -= money(after * TIER_RATES.get(order.customer.tier, Decimal("0"))) + code = (order.coupon or "").upper() + if code in COUPON_PERCENT: + after -= money(after * COUPON_PERCENT[code]) + elif code in COUPON_FLAT and sub >= COUPON_FLAT_MIN_SUBTOTAL: + after -= min(COUPON_FLAT[code], after) + return after diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/export.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/export.py new file mode 100644 index 00000000..b51eadae --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/export.py @@ -0,0 +1,36 @@ +from .currency import money +from .discounts import discount_for_order, order_subtotal +from .orders import calc_total +from .shipping import shipping_cost +from .tax import tax_for_order + +CSV_HEADER = ("order_id", "customer", "date", "subtotal", "discount", "tax", "shipping", "total") + + +def order_row(order): + when = order.placed_on.isoformat() if order.placed_on else "" + return [ + order.order_id, + order.customer.cid, + when, + str(money(order_subtotal(order))), + str(money(discount_for_order(order))), + str(money(tax_for_order(order))), + str(money(shipping_cost(order))), + str(money(calc_total(order))), + ] + + +def orders_to_csv(orders): + rows = [",".join(CSV_HEADER)] + for order in orders: + rows.append(",".join(order_row(order))) + return "\n".join(rows) + "\n" + + +def column_sums(orders): + sums = [money(0)] * 5 + for order in orders: + for i, cell in enumerate(order_row(order)[3:]): + sums[i] = sums[i] + money(cell) + return dict(zip(CSV_HEADER[3:], sums)) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/inventory.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/inventory.py new file mode 100644 index 00000000..fb6cb2dc --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/inventory.py @@ -0,0 +1,55 @@ +LOW_STOCK_THRESHOLD = 5 + + +class OutOfStock(Exception): + pass + + +class Inventory: + def __init__(self, stock=None): + self.stock = dict(stock or {}) + self.reserved = {} + + def available(self, sku): + return self.stock.get(sku, 0) - self.reserved.get(sku, 0) + + def restock(self, sku, qty): + self.stock[sku] = self.stock.get(sku, 0) + qty + + def reserve(self, sku, qty): + if qty > self.available(sku): + raise OutOfStock("%s: wanted %d, have %d" % (sku, qty, self.available(sku))) + self.reserved[sku] = self.reserved.get(sku, 0) + qty + + def release(self, sku, qty): + have = self.reserved.get(sku, 0) + self.reserved[sku] = max(have - qty, 0) + + def ship(self, sku, qty): + self.stock[sku] = self.stock.get(sku, 0) - qty + self.release(sku, qty) + + +def low_stock(inv, threshold=None): + if threshold is None: + threshold = LOW_STOCK_THRESHOLD + return sorted(sku for sku in inv.stock if inv.available(sku) <= threshold) + + +def reserve_order(inv, order): + done = [] + try: + for line in order.lines: + inv.reserve(line.product.sku, line.qty) + done.append(line) + except OutOfStock: + for line in done: + inv.release(line.product.sku, line.qty) + raise + + +def dump_stock_csv(inv): + rows = ["sku,stock,reserved"] + for sku in sorted(inv.stock): + rows.append("%s,%d,%d" % (sku, inv.stock[sku], inv.reserved.get(sku, 0))) + return "\n".join(rows) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/invoices.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/invoices.py new file mode 100644 index 00000000..199c1c60 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/invoices.py @@ -0,0 +1,125 @@ +import re +from dataclasses import dataclass +from datetime import date, timedelta +from decimal import Decimal +from typing import List, Tuple + +from .currency import fmt_money, money +from .discounts import ( + COUPON_FLAT, + COUPON_FLAT_MIN_SUBTOTAL, + COUPON_PERCENT, + TIER_RATES, + VOLUME_DISCOUNT_MIN_QTY, + VOLUME_DISCOUNT_RATE, +) +from .shipping import ( + FREE_SHIPPING_THRESHOLD, + FREE_WEIGHT_KG, + HOME_COUNTRY, + INTERNATIONAL_SURCHARGE, + PER_KG_RATE, + SHIPPING_FLAT, +) +from .tax import REGION_RATES, TAX_RATE + +INVOICE_DUE_DAYS = 14 + + +@dataclass +class Invoice: + number: str + order_id: str + customer_name: str + rows: List[Tuple[str, int, Decimal]] + subtotal: Decimal + discount: Decimal + tax: Decimal + shipping: Decimal + total: Decimal + issued: str + due: str + + +def invoice_number(order): + digits = "".join(ch for ch in order.order_id if ch.isdigit()) + return "INV-" + digits.zfill(5) + + +def parse_due_date(text): + m = re.match(r"^\s*(\d{4})[-/](\d{2})[-/](\d{2})\s*$", text) + if not m: + raise ValueError("bad due date: %r" % text) + return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + + +def build_invoice(order, issued=None): + if issued is None: + issued = order.placed_on + if issued is None: + raise ValueError("order %s has no date" % order.order_id) + sub = Decimal("0") + vol = Decimal("0") + rows = [] + for ln in order.lines: + amount = ln.product.price * ln.qty + sub += amount + rows.append((ln.product.sku, ln.qty, amount)) + if ln.qty >= VOLUME_DISCOUNT_MIN_QTY: + vol += money(amount * VOLUME_DISCOUNT_RATE) + rest = sub - vol + tier = money(rest * TIER_RATES.get(order.customer.tier, 0)) + rest -= tier + coupon = Decimal("0") + code = (order.coupon or "").upper() + if code in COUPON_PERCENT: + coupon = money(rest * COUPON_PERCENT[code]) + elif code in COUPON_FLAT and sub >= COUPON_FLAT_MIN_SUBTOTAL: + coupon = min(COUPON_FLAT[code], rest) + discount = vol + tier + coupon + net = sub - discount + vat = REGION_RATES.get(order.ship_country, TAX_RATE) + if order.customer.tax_exempt: + vat = Decimal("0") + tax = money(net * vat) + ship = Decimal("0.00") + if rows and net < FREE_SHIPPING_THRESHOLD: + ship = SHIPPING_FLAT + kg = Decimal("0") + for ln in order.lines: + kg += ln.product.weight_kg * ln.qty + if kg > FREE_WEIGHT_KG: + ship += money((kg - FREE_WEIGHT_KG) * PER_KG_RATE) + if order.ship_country != HOME_COUNTRY: + ship += INTERNATIONAL_SURCHARGE + due = issued + timedelta(days=INVOICE_DUE_DAYS) + return Invoice( + number=invoice_number(order), + order_id=order.order_id, + customer_name=order.customer.name, + rows=rows, + subtotal=sub, + discount=discount, + tax=tax, + shipping=ship, + total=net + tax + ship, + issued=issued.isoformat(), + due=due.isoformat(), + ) + + +def format_invoice(inv): + out = ["Invoice %s for %s" % (inv.number, inv.customer_name)] + for sku, qty, amount in inv.rows: + out.append(" %-6s x%-3d %10s" % (sku, qty, fmt_money(amount))) + out.append(" subtotal %s" % fmt_money(inv.subtotal)) + if inv.discount: + out.append(" discount -%s" % fmt_money(inv.discount)) + out.append(" tax %s" % fmt_money(inv.tax)) + out.append(" shipping %s" % fmt_money(inv.shipping)) + out.append(" TOTAL %s EUR, due %s" % (fmt_money(inv.total), inv.due)) + return "\n".join(out) + + +def is_overdue(inv, today_text): + return parse_due_date(today_text) > parse_due_date(inv.due) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/loyalty.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/loyalty.py new file mode 100644 index 00000000..56d3c47d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/loyalty.py @@ -0,0 +1,24 @@ +from decimal import Decimal + +from .currency import money +from .discounts import compute_order_total + +LOYALTY_POINTS_PER_UNIT = 1 +TIER_MULTIPLIERS = { + "bronze": Decimal("1"), + "silver": Decimal("1.25"), + "gold": Decimal("1.5"), + "platinum": Decimal("2"), +} +POINT_VALUE = Decimal("0.01") + + +def points_for_order(order): + """Whole points earned on the net total of an order.""" + net = compute_order_total(order) + mult = TIER_MULTIPLIERS.get(order.customer.tier, Decimal("1")) + return int(net * LOYALTY_POINTS_PER_UNIT * mult) + + +def redeem_value(points): + return money(points * POINT_VALUE) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/notifications.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/notifications.py new file mode 100644 index 00000000..9e9f6843 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/notifications.py @@ -0,0 +1,22 @@ +from .currency import fmt_money +from .orders import calc_total +from .products import get_product +from .util import join_nonempty + + +def order_confirmation(order): + total = calc_total(order) + lines = ["Dear %s," % order.customer.name, "", "thank you for your order %s." % order.order_id] + for line in order.lines: + lines.append(" %dx %s" % (line.qty, line.product.name)) + lines.append("Total: %s EUR" % fmt_money(total)) + if order.coupon: + lines.append("Coupon applied: %s" % order.coupon.upper()) + return "\n".join(lines) + + +def low_stock_alert(skus): + if not skus: + return "" + names = [get_product(s).name for s in skus] + return join_nonempty(["Low stock", ", ".join(names)], sep=": ") diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/orders.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/orders.py new file mode 100644 index 00000000..9783c16c --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/orders.py @@ -0,0 +1,133 @@ +from dataclasses import dataclass, field +from datetime import date, datetime +from decimal import ROUND_HALF_UP, Decimal +from typing import List, Optional + +from .currency import fmt_money +from .customers import Cust +from .discounts import ( + COUPON_FLAT, + COUPON_FLAT_MIN_SUBTOTAL, + COUPON_PERCENT, + TIER_RATES, + VOLUME_DISCOUNT_MIN_QTY, + VOLUME_DISCOUNT_RATE, +) +from .products import Product +from .shipping import ( + FREE_SHIPPING_THRESHOLD, + FREE_WEIGHT_KG, + HOME_COUNTRY, + INTERNATIONAL_SURCHARGE, + PER_KG_RATE, + SHIPPING_FLAT, +) +from .tax import REGION_RATES, TAX_RATE + + +@dataclass +class OrderLine: + product: Product + qty: int + + +@dataclass +class Order: + order_id: str + customer: Cust + lines: List[OrderLine] = field(default_factory=list) + coupon: Optional[str] = None + ship_country: str = "DE" + placed_on: Optional[date] = None + status: str = "new" + + +def parse_order_date(text): + text = text.strip() + for fmt in ("%d.%m.%Y", "%Y-%m-%d"): + try: + return datetime.strptime(text, fmt).date() + except ValueError: + pass + raise ValueError("cannot parse order date: %r" % text) + + +def new_order(order_id, customer, coupon=None, ship_country=None, placed_on=None): + return Order( + order_id=order_id, + customer=customer, + coupon=coupon, + ship_country=ship_country or customer.country, + placed_on=placed_on, + ) + + +def add_line(order, product, qty): + if qty <= 0: + raise ValueError("quantity must be positive") + for line in order.lines: + if line.product.sku == product.sku: + line.qty += qty + return line + line = OrderLine(product, qty) + order.lines.append(line) + return line + + +def remove_line(order, sku): + before = len(order.lines) + order.lines = [l for l in order.lines if l.product.sku != sku] + return len(order.lines) != before + + +def order_weight(order): + kg = Decimal("0") + for line in order.lines: + kg += line.product.weight_kg * line.qty + return kg + + +def calc_total(order): + """Grand total: goods - discounts + tax + shipping.""" + sub = Decimal("0") + vol = Decimal("0") + for ln in order.lines: + amt = ln.product.price * ln.qty + sub += amt + if ln.qty >= VOLUME_DISCOUNT_MIN_QTY: + vol += (amt * VOLUME_DISCOUNT_RATE).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + net = sub - vol + tier_rate = TIER_RATES.get(order.customer.tier) + if tier_rate: + net -= (net * tier_rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + code = (order.coupon or "").upper() + if code in COUPON_PERCENT: + net -= (net * COUPON_PERCENT[code]).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + elif code in COUPON_FLAT and sub >= COUPON_FLAT_MIN_SUBTOTAL: + net -= min(COUPON_FLAT[code], net) + rate = REGION_RATES.get(order.ship_country, TAX_RATE) + if order.customer.tax_exempt: + rate = Decimal("0") + tax = (net * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + ship = Decimal("0") + if order.lines and net < FREE_SHIPPING_THRESHOLD: + ship = SHIPPING_FLAT + kg = order_weight(order) + if kg > FREE_WEIGHT_KG: + ship += ((kg - FREE_WEIGHT_KG) * PER_KG_RATE).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + if order.ship_country != HOME_COUNTRY: + ship += INTERNATIONAL_SURCHARGE + return net + tax + ship + + +def order_summary(order): + return "Order %s: %d lines, total %s EUR" % ( + order.order_id, + len(order.lines), + fmt_money(calc_total(order)), + ) + + +def old_order_summary(order): + parts = ["%s x%d" % (l.product.sku, l.qty) for l in order.lines] + return "%s (%s)" % (order.order_id, " ".join(parts)) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/products.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/products.py new file mode 100644 index 00000000..0d4d3019 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/products.py @@ -0,0 +1,64 @@ +from dataclasses import dataclass +from decimal import Decimal + + +@dataclass(frozen=True) +class Product: + sku: str + name: str + price: Decimal + weight_kg: Decimal + category: str = "general" + active: bool = True + + +def default_catalog(): + return [ + Product("P-100", "Notebook A5", Decimal("4.50"), Decimal("0.30"), "stationery"), + Product("P-101", "Ballpoint pens (10)", Decimal("3.20"), Decimal("0.10"), "stationery"), + Product("P-102", "Desk lamp", Decimal("24.90"), Decimal("1.20"), "home"), + Product("P-103", "USB cable 1m", Decimal("6.99"), Decimal("0.08"), "electronics"), + Product("P-104", "Wireless mouse", Decimal("18.75"), Decimal("0.12"), "electronics"), + Product("P-105", "Mechanical keyboard", Decimal("89.00"), Decimal("1.10"), "electronics"), + Product("P-106", "Monitor stand", Decimal("35.00"), Decimal("2.80"), "home"), + Product("P-107", "Coffee beans 1kg", Decimal("14.20"), Decimal("1.05"), "food"), + Product("P-108", "Tea sampler", Decimal("9.90"), Decimal("0.40"), "food"), + Product("P-109", "Office chair", Decimal("129.00"), Decimal("9.50"), "furniture"), + Product("P-110", "Whiteboard 90x60", Decimal("42.50"), Decimal("3.90"), "office"), + Product("P-111", "E-book bundle", Decimal("12.00"), Decimal("0"), "digital"), + Product("P-112", "Fax paper roll", Decimal("2.10"), Decimal("0.25"), "office", active=False), + ] + + +_by_sku = {} + + +def get_product(sku): + if not _by_sku: + for p in default_catalog(): + _by_sku[p.sku] = p + try: + return _by_sku[sku] + except KeyError: + raise KeyError("unknown sku: %s" % sku) + + +def price_of(sku): + return get_product(sku).price + + +def find_products(category): + return [p for p in default_catalog() if p.category == category and p.active] + + +def search_products(term): + term = term.lower() + return [p for p in default_catalog() if term in p.name.lower() and p.active] + + +def legacy_price_lookup(sku): + """Old price list lookup, kept from the spreadsheet import.""" + for p in default_catalog(): + if p.sku == sku: + return p.price + return None diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/reports.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/reports.py new file mode 100644 index 00000000..45038431 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/reports.py @@ -0,0 +1,115 @@ +from datetime import date +from decimal import Decimal + +from .currency import fmt_money, fmt_pct +from .customers import suggest_tier +from .discounts import compute_order_total +from .inventory import low_stock +from .orders import calc_total +from .tax import order_total_with_tax, tax_for_order +from .util import truncate + +AGING_BUCKET_DAYS = 30 +MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + + +def _to_date(text): + text = (text or "").strip() + try: + if "-" in text: + y, m, d = text.split("-") + return date(int(y), int(m), int(d)) + if "/" in text: + d, m, y = text.split("/") + return date(int(y), int(m), int(d)) + if "," in text: + md, y = text.split(",") + mon, d = md.split() + return date(int(y), MONTHS.index(mon[:3].title()) + 1, int(d)) + except ValueError: + return None + return None + + +def sales_report(orders): + print("SALES REPORT") + print("=" * 40) + grand = Decimal("0") + for o in sorted(orders, key=lambda o: o.order_id): + total = calc_total(o) + grand += total + print("%-8s %-16s %12s" % (o.order_id, truncate(o.customer.name, 16), fmt_money(total))) + print("-" * 40) + print("%-25s %12s" % ("TOTAL", fmt_money(grand))) + print("%d orders" % len(orders)) + + +def customer_report(customers, orders): + print("CUSTOMER REPORT") + print("=" * 40) + for c in sorted(customers, key=lambda c: c.cid): + mine = [o for o in orders if o.customer.cid == c.cid] + spend = sum((order_total_with_tax(o) for o in mine), Decimal("0")) + line = "%-5s %-14s %-9s %2d orders %10s" % ( + c.cid, + truncate(c.name, 14), + c.tier, + len(mine), + fmt_money(spend), + ) + better = suggest_tier(spend) + if better != c.tier and better != "bronze": + line += " suggest %s" % better + print(line) + + +def inventory_report(inv, catalog): + print("INVENTORY REPORT") + print("=" * 40) + low = set(low_stock(inv)) + value = Decimal("0") + for p in sorted(catalog, key=lambda p: p.sku): + have = inv.available(p.sku) + value += p.price * max(have, 0) + flag = " LOW" if p.sku in low else "" + print("%-6s %-22s %5d%s" % (p.sku, truncate(p.name, 22), have, flag)) + print("stock value %s" % fmt_money(value)) + + +def tax_summary(orders): + print("TAX SUMMARY") + print("=" * 40) + countries = sorted(set(o.ship_country for o in orders)) + all_net = Decimal("0") + all_tax = Decimal("0") + for cc in countries: + net = Decimal("0") + tax = Decimal("0") + for o in orders: + if o.ship_country == cc: + net += compute_order_total(o) + tax += tax_for_order(o) + rate = tax / net if net else Decimal("0") + print("%-3s net %10s tax %9s (%s)" % (cc, fmt_money(net), fmt_money(tax), fmt_pct(rate))) + all_net += net + all_tax += tax + print("ALL net %10s tax %9s" % (fmt_money(all_net), fmt_money(all_tax))) + + +def aging_report(invoices, today_text): + print("AGING REPORT as of %s" % today_text) + print("=" * 40) + today = _to_date(today_text) + for inv in sorted(invoices, key=lambda i: i.number): + due = _to_date(inv.due) + if due is None or today is None: + bucket = "n/a" + else: + late = (today - due).days + if late <= 0: + bucket = "current" + elif late <= AGING_BUCKET_DAYS: + bucket = "1-%d days" % AGING_BUCKET_DAYS + else: + bucket = "over %d days" % AGING_BUCKET_DAYS + print("%-10s %-12s %10s %s" % (inv.number, inv.due, fmt_money(inv.total), bucket)) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/returns.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/returns.py new file mode 100644 index 00000000..7c6eda58 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/returns.py @@ -0,0 +1,30 @@ +from decimal import Decimal + +from .currency import money +from .discounts import order_subtotal +from .tax import order_total_with_tax + +RETURN_WINDOW_DAYS = 30 +RESTOCKING_FEE_RATE = Decimal("0.10") + + +def can_return(order, today): + if order.placed_on is None or order.status == "cancelled": + return False + return (today - order.placed_on).days <= RETURN_WINDOW_DAYS + + +def refund_amount(order, sku, qty): + """Refund for returning qty units of sku: its share of net + tax, minus the restocking fee.""" + line = None + for candidate in order.lines: + if candidate.product.sku == sku: + line = candidate + if line is None: + raise KeyError("order %s has no line %s" % (order.order_id, sku)) + if qty <= 0 or qty > line.qty: + raise ValueError("cannot return %d of %d" % (qty, line.qty)) + share = (line.product.price * qty) / order_subtotal(order) + base = order_total_with_tax(order) * share + fee = money(base * RESTOCKING_FEE_RATE) + return money(base) - fee diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/sample.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/sample.py new file mode 100644 index 00000000..0811b620 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/sample.py @@ -0,0 +1,48 @@ +"""Demo data used by the command line tool and by the tests.""" + +from .customers import load_customers +from .inventory import Inventory +from .storage import parse_orders + +CUSTOMERS_CSV = """ +# cid, name, email, tier, country, joined, tax exempt +c001, Anna Becker, anna@example.org, gold, DE, 2019-03-14, 0 +c002, Luc Martin, luc@example.fr, silver, FR, 2021-07-02, 0 +c003, Joe Smith, joe@example.com, bronze, US, 2023-01-20, 0 +c004, Mira Novak, mira@example.cz, platinum, CZ, 2018-11-30, 0 +c005, Acme GmbH, buchhaltung@acme.example, silver, DE, 2020-05-05, 1 +c006, Sven Berg, sven@example.se, bronze, SE, 2024-02-29, 0 +""" + +ORDERS_TEXT = """ +# order; customer; items; coupon; country; date +O-1001; c001; P-100:12,P-105:1; WELCOME10; DE; 2024-03-04 +O-1002; c002; P-102:2,P-103:3; ; FR; 05.03.2024 +O-1003; c003; P-109:1; SAVE5; US; 2024-03-06 +O-1004; c004; P-107:4,P-108:2; ; CZ; 07.03.2024 +O-1005; c005; P-110:3,P-106:2; BULK20; DE; 2024-03-08 +O-1006; c006; P-101:20,P-111:1; ; SE; 2024-03-11 +O-1007; c001; P-104:1; ; DE; 12.03.2024 +O-1008; c003; P-100:2,P-103:1; ; US; 2024-03-15 +""" + +STOCK = { + "P-100": 40, + "P-101": 100, + "P-102": 8, + "P-103": 60, + "P-104": 3, + "P-105": 6, + "P-106": 12, + "P-107": 25, + "P-108": 4, + "P-109": 2, + "P-110": 7, + "P-111": 999, +} + + +def load_demo(): + customers = load_customers(CUSTOMERS_CSV) + orders = parse_orders(ORDERS_TEXT, customers) + return customers, orders, Inventory(STOCK) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/shipping.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/shipping.py new file mode 100644 index 00000000..3cc90c47 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/shipping.py @@ -0,0 +1,42 @@ +from decimal import Decimal + +from .currency import money +from .discounts import compute_order_total + +FREE_SHIPPING_THRESHOLD = Decimal("100.00") +SHIPPING_FLAT = Decimal("6.50") +FREE_WEIGHT_KG = Decimal("5") +PER_KG_RATE = Decimal("1.20") +INTERNATIONAL_SURCHARGE = Decimal("8.00") +HOME_COUNTRY = "DE" + + +def parcel_weight(order): + return sum((line.product.weight_kg * line.qty for line in order.lines), Decimal("0")) + + +def is_free_shipping(order): + return compute_order_total(order) >= FREE_SHIPPING_THRESHOLD + + +def shipping_cost(order): + if not order.lines: + return Decimal("0.00") + if is_free_shipping(order): + return Decimal("0.00") + cost = SHIPPING_FLAT + over = parcel_weight(order) - FREE_WEIGHT_KG + if over > 0: + cost += money(over * PER_KG_RATE) + if order.ship_country != HOME_COUNTRY: + cost += INTERNATIONAL_SURCHARGE + return cost + + +def estimate_zone_v1(country): + """Zone lookup used before the international surcharge existed.""" + if country == "DE": + return 1 + if country in ("FR", "NL", "BE", "AT"): + return 2 + return 3 diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/storage.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/storage.py new file mode 100644 index 00000000..15af8213 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/storage.py @@ -0,0 +1,37 @@ +from .customers import find_customer +from .orders import add_line, new_order, parse_order_date +from .products import get_product + + +def parse_orders(text, customers): + """Parse lines of ``order;customer;sku:qty,sku:qty;coupon;country;date``.""" + orders = [] + for raw in text.strip().splitlines(): + raw = raw.strip() + if not raw or raw.startswith("#"): + continue + order_id, cid, items, coupon, country, when = [f.strip() for f in raw.split(";")] + cust = find_customer(customers, cid) + if cust is None: + raise KeyError("unknown customer: %s" % cid) + order = new_order( + order_id, + cust, + coupon=coupon or None, + ship_country=country or None, + placed_on=parse_order_date(when) if when else None, + ) + for item in items.split(","): + sku, qty = item.split(":") + add_line(order, get_product(sku.strip()), int(qty)) + orders.append(order) + return orders + + +def dump_orders(orders): + rows = [] + for o in orders: + items = ",".join("%s:%d" % (l.product.sku, l.qty) for l in o.lines) + when = o.placed_on.isoformat() if o.placed_on else "" + rows.append(";".join([o.order_id, o.customer.cid, items, o.coupon or "", o.ship_country, when])) + return "\n".join(rows) + "\n" diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/tax.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/tax.py new file mode 100644 index 00000000..c8925118 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/tax.py @@ -0,0 +1,42 @@ +from decimal import ROUND_HALF_UP, Decimal + +from .currency import money +from .discounts import compute_order_total + +TAX_RATE = Decimal("0.19") +REGION_RATES = { + "FR": Decimal("0.20"), + "US": Decimal("0.07"), + "CH": Decimal("0.081"), + "SE": Decimal("0.25"), +} + + +def rate_for(country, customer=None): + if customer is not None and customer.tax_exempt: + return Decimal("0") + return REGION_RATES.get(country, TAX_RATE) + + +def tax_for_order(order): + net = compute_order_total(order) + return money(net * rate_for(order.ship_country, order.customer)) + + +def order_total_with_tax(order): + """Net total plus tax; shipping is not part of it.""" + net = compute_order_total(order) + rate = TAX_RATE + if order.ship_country in REGION_RATES: + rate = REGION_RATES[order.ship_country] + if order.customer.tax_exempt: + rate = Decimal("0") + return net + (net * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + +def tax_breakdown(orders): + """Tax collected per shipping country.""" + result = {} + for order in orders: + result[order.ship_country] = result.get(order.ship_country, Decimal("0")) + tax_for_order(order) + return result diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/util.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/util.py new file mode 100644 index 00000000..67910ba3 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/util.py @@ -0,0 +1,17 @@ +import re + + +def truncate(text, width): + if len(text) <= width: + return text + return text[: width - 1] + "~" + + +def slugify(text): + """Make a url friendly name (used by the old web shop export).""" + text = re.sub(r"[^a-z0-9]+", "-", text.lower()) + return text.strip("-") + + +def join_nonempty(parts, sep=", "): + return sep.join(p for p in parts if p) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/shop/validation.py b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/validation.py new file mode 100644 index 00000000..58a7a585 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/shop/validation.py @@ -0,0 +1,34 @@ +import re + +MAX_LINE_QTY = 100 +MAX_ORDER_LINES = 25 +KNOWN_COUNTRIES = ("DE", "FR", "US", "CZ", "SE", "CH", "AT", "NL") + + +class ValidationError(ValueError): + pass + + +def validate_order(order): + """Return a list of problems; an empty list means the order is fine.""" + problems = [] + if not order.lines: + problems.append("order has no lines") + if len(order.lines) > MAX_ORDER_LINES: + problems.append("too many lines: %d" % len(order.lines)) + for line in order.lines: + if line.qty > MAX_LINE_QTY: + problems.append("%s: quantity %d exceeds %d" % (line.product.sku, line.qty, MAX_LINE_QTY)) + if not line.product.active: + problems.append("%s: product is not active" % line.product.sku) + if order.ship_country not in KNOWN_COUNTRIES: + problems.append("unknown country: %s" % order.ship_country) + if order.coupon and not re.match(r"^[A-Z]+[0-9]+$", order.coupon.upper()): + problems.append("malformed coupon: %s" % order.coupon) + return problems + + +def ensure_valid(order): + problems = validate_order(order) + if problems: + raise ValidationError("; ".join(problems)) diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/helpers.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/helpers.py new file mode 100644 index 00000000..5d662c92 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/helpers.py @@ -0,0 +1,42 @@ +import contextlib +import io +from datetime import date + +from shop.cli import main +from shop.customers import Cust +from shop.orders import add_line, new_order +from shop.products import get_product + + +def customer(cid="c900", tier="bronze", country="DE", exempt=False): + return Cust(cid, "Test " + cid, cid + "@example.org", tier, country, date(2020, 1, 1), exempt) + + +def order_with(items, tier="bronze", country="DE", coupon=None, exempt=False, order_id="T-1", placed_on=date(2024, 3, 1)): + order = new_order( + order_id, + customer(tier=tier, country=country, exempt=exempt), + coupon=coupon, + ship_country=country, + placed_on=placed_on, + ) + for sku, qty in items: + add_line(order, get_product(sku), qty) + return order + + +def run_cli(*argv): + """Run the command line tool, return (exit code, stdout).""" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(list(argv)) + return code, buf.getvalue() + + +def render(fn, *args, **kwargs): + """Text produced by a report function, whether it returns it or prints it.""" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + result = fn(*args, **kwargs) + text = result if isinstance(result, str) else buf.getvalue() + return text.rstrip("\n") diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_discounts.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_discounts.py new file mode 100644 index 00000000..4924692d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_discounts.py @@ -0,0 +1,64 @@ +import unittest +from decimal import Decimal + +from helpers import order_with +from shop.discounts import describe_discount, discount_for_order +from shop.sample import load_demo + + +class DiscountTests(unittest.TestCase): + def test_volume_discount_on_large_line(self): + order = order_with([("P-100", 10)]) + self.assertEqual(discount_for_order(order), Decimal("2.25")) + self.assertEqual(describe_discount(order), "volume 2.25") + + def test_no_volume_discount_below_ten(self): + order = order_with([("P-100", 9)]) + self.assertEqual(discount_for_order(order), Decimal("0")) + self.assertEqual(describe_discount(order), "none") + + def test_gold_tier_discount(self): + order = order_with([("P-105", 1)], tier="gold") + self.assertEqual(discount_for_order(order), Decimal("6.23")) + self.assertEqual(describe_discount(order), "tier 6.23") + + def test_platinum_tier_discount(self): + order = order_with([("P-102", 2)], tier="platinum") + self.assertEqual(discount_for_order(order), Decimal("4.98")) + + def test_percent_coupon_after_tier(self): + order = order_with([("P-102", 2)], tier="silver", coupon="WELCOME10") + self.assertEqual(discount_for_order(order), Decimal("6.32")) + self.assertEqual(describe_discount(order), "tier 1.49, coupon 4.83") + + def test_coupon_code_is_case_insensitive(self): + order = order_with([("P-107", 4)], coupon="welcome10") + self.assertEqual(discount_for_order(order), Decimal("5.68")) + + def test_flat_coupon_needs_minimum_subtotal(self): + order = order_with([("P-100", 2)], coupon="SAVE5") + self.assertEqual(discount_for_order(order), Decimal("0")) + + def test_flat_coupon_applies_over_minimum(self): + order = order_with([("P-107", 4)], coupon="SAVE5") + self.assertEqual(discount_for_order(order), Decimal("5.00")) + + def test_unknown_coupon_is_ignored(self): + order = order_with([("P-107", 4)], coupon="NOPE50") + self.assertEqual(discount_for_order(order), Decimal("0")) + + def test_all_discounts_combined(self): + _customers, orders, _inv = load_demo() + order = orders[0] + self.assertEqual(order.order_id, "O-1001") + self.assertEqual(discount_for_order(order), Decimal("25.57")) + self.assertEqual(describe_discount(order), "volume 2.70, tier 9.82, coupon 13.05") + + def test_bulk_coupon_with_silver_tier(self): + _customers, orders, _inv = load_demo() + order = orders[4] + self.assertEqual(describe_discount(order), "tier 5.93, coupon 20.00") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_extras.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_extras.py new file mode 100644 index 00000000..c9de45eb --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_extras.py @@ -0,0 +1,121 @@ +import unittest +from decimal import Decimal + +from helpers import customer, run_cli +from shop.analytics import ( + average_order_value, + best_customers, + orders_between, + repeat_customer_ids, + revenue_by_month, + top_products, +) +from shop.cart import Cart +from shop.export import column_sums, orders_to_csv +from shop.sample import load_demo + + +class AnalyticsTests(unittest.TestCase): + def setUp(self): + _c, self.orders, _inv = load_demo() + + def test_revenue_by_month(self): + self.assertEqual(revenue_by_month(self.orders), {"2024-03": Decimal("801.77")}) + + def test_orders_between_mixed_date_styles(self): + picked = orders_between(self.orders, "2024-03-05", "08.03.2024") + self.assertEqual([o.order_id for o in picked], ["O-1002", "O-1003", "O-1004", "O-1005"]) + + def test_orders_between_empty_window(self): + self.assertEqual(orders_between(self.orders, "2025-01-01", "2025-01-31"), []) + + def test_top_products(self): + self.assertEqual(top_products(self.orders), [("P-101", 20), ("P-100", 14), ("P-103", 4)]) + self.assertEqual(len(top_products(self.orders, 5)), 5) + + def test_average_order_value(self): + self.assertEqual(average_order_value(self.orders), Decimal("100.22")) + self.assertEqual(average_order_value([]), Decimal("0.00")) + + def test_best_customers_by_spend_with_tax(self): + best = best_customers(self.orders, 2) + self.assertEqual(best, [("c005", Decimal("171.57")), ("c001", Decimal("160.49"))]) + + def test_repeat_customers(self): + self.assertEqual(repeat_customer_ids(self.orders), ["c001", "c003"]) + + +class ExportTests(unittest.TestCase): + def test_csv_export(self): + _c, orders, _inv = load_demo() + lines = orders_to_csv(orders).splitlines() + self.assertEqual(lines[0], "order_id,customer,date,subtotal,discount,tax,shipping,total") + self.assertEqual(lines[1], "O-1001,c001,2024-03-04,143.00,25.57,22.31,0.00,139.74") + self.assertEqual(lines[5], "O-1005,c005,2024-03-08,197.50,25.93,0.00,0.00,171.57") + self.assertEqual(len(lines), 9) + + def test_column_sums(self): + _c, orders, _inv = load_demo() + self.assertEqual( + column_sums(orders), + { + "subtotal": Decimal("727.61"), + "discount": Decimal("70.79"), + "tax": Decimal("80.45"), + "shipping": Decimal("64.50"), + "total": Decimal("801.77"), + }, + ) + + def test_cli_export_matches_function(self): + _c, orders, _inv = load_demo() + self.assertEqual(run_cli("export"), (0, orders_to_csv(orders))) + + def test_cli_stats(self): + code, out = run_cli("stats") + self.assertEqual(code, 0) + self.assertEqual( + out.splitlines(), + ["2024-03 801.77", "average order 100.22", "top products: P-101 x20, P-100 x14, P-103 x4"], + ) + + +class CartTests(unittest.TestCase): + def test_estimate_matches_order_total(self): + cart = Cart(customer(tier="gold"), coupon="WELCOME10") + cart.add("P-100", 12) + cart.add("P-105") + self.assertEqual(cart.count(), 13) + self.assertEqual( + cart.estimate(), + { + "net": Decimal("117.43"), + "tax": Decimal("22.31"), + "shipping": Decimal("0.00"), + "total": Decimal("139.74"), + }, + ) + + def test_estimate_with_shipping(self): + cart = Cart(customer(country="US")) + cart.add("P-103") + self.assertEqual(cart.estimate()["total"], Decimal("21.98")) + + def test_remove_and_unknown_sku(self): + cart = Cart(customer()) + cart.add("P-100", 2) + self.assertTrue(cart.remove("P-100")) + self.assertFalse(cart.remove("P-100")) + with self.assertRaises(KeyError): + cart.add("P-999") + + def test_to_order_sorts_lines_by_sku(self): + cart = Cart(customer()) + cart.add("P-105") + cart.add("P-100", 3) + order = cart.to_order("C-1") + self.assertEqual([(l.product.sku, l.qty) for l in order.lines], [("P-100", 3), ("P-105", 1)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_invoices.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_invoices.py new file mode 100644 index 00000000..286cedce --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_invoices.py @@ -0,0 +1,94 @@ +import unittest +from datetime import date +from decimal import Decimal + +from helpers import order_with +from shop.invoices import build_invoice, format_invoice, invoice_number, is_overdue +from shop.sample import load_demo + + +class InvoiceTests(unittest.TestCase): + def setUp(self): + _customers, self.orders, _inv = load_demo() + + def test_number_comes_from_order_id(self): + self.assertEqual(invoice_number(self.orders[1]), "INV-01002") + self.assertEqual(invoice_number(order_with([], order_id="X-77")), "INV-00077") + + def test_amounts_with_international_shipping(self): + inv = build_invoice(self.orders[1]) + self.assertEqual(inv.subtotal, Decimal("70.77")) + self.assertEqual(inv.discount, Decimal("2.12")) + self.assertEqual(inv.tax, Decimal("13.73")) + self.assertEqual(inv.shipping, Decimal("14.50")) + self.assertEqual(inv.total, Decimal("96.88")) + + def test_amounts_with_free_shipping(self): + inv = build_invoice(self.orders[0]) + self.assertEqual( + (inv.subtotal, inv.discount, inv.tax, inv.shipping, inv.total), + (Decimal("143.00"), Decimal("25.57"), Decimal("22.31"), Decimal("0"), Decimal("139.74")), + ) + + def test_tax_exempt_customer(self): + inv = build_invoice(self.orders[4]) + self.assertEqual(inv.tax, Decimal("0")) + self.assertEqual(inv.total, Decimal("171.57")) + + def test_every_demo_invoice_total(self): + totals = [str(build_invoice(o).total) for o in self.orders] + self.assertEqual( + totals, + ["139.74", "96.88", "132.68", "96.54", "171.57", "105.50", "27.25", "31.61"], + ) + + def test_dates(self): + inv = build_invoice(self.orders[1]) + self.assertEqual((inv.issued, inv.due), ("2024-03-05", "2024-03-19")) + later = build_invoice(self.orders[1], issued=date(2024, 12, 20)) + self.assertEqual((later.issued, later.due), ("2024-12-20", "2025-01-03")) + + def test_order_without_date_is_rejected(self): + order = order_with([("P-100", 1)], placed_on=None) + with self.assertRaises(ValueError): + build_invoice(order) + + def test_rows(self): + inv = build_invoice(self.orders[0]) + self.assertEqual(inv.rows, [("P-100", 12, Decimal("54.00")), ("P-105", 1, Decimal("89.00"))]) + + def test_formatted_invoice(self): + text = format_invoice(build_invoice(self.orders[0])) + self.assertEqual( + text.splitlines(), + [ + "Invoice INV-01001 for Anna Becker", + " P-100 x12 54.00", + " P-105 x1 89.00", + " subtotal 143.00", + " discount -25.57", + " tax 22.31", + " shipping 0.00", + " TOTAL 139.74 EUR, due 2024-03-18", + ], + ) + + def test_no_discount_line_without_discount(self): + text = format_invoice(build_invoice(self.orders[7])) + self.assertNotIn("discount", text) + + def test_overdue_accepts_several_date_styles(self): + inv = build_invoice(self.orders[0]) + self.assertEqual(inv.due, "2024-03-18") + self.assertFalse(is_overdue(inv, "2024-03-18")) + self.assertTrue(is_overdue(inv, "2024-03-19")) + self.assertTrue(is_overdue(inv, "2024/03/20")) + + def test_overdue_rejects_garbage(self): + inv = build_invoice(self.orders[0]) + with self.assertRaises(ValueError): + is_overdue(inv, "yesterday") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_orders_customers.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_orders_customers.py new file mode 100644 index 00000000..0d44488d --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_orders_customers.py @@ -0,0 +1,123 @@ +import unittest +from datetime import date + +from helpers import customer, order_with +from shop.customers import ( + Cust, + customers_by_tier, + find_customer, + is_valid_email, + load_customers, + suggest_tier, + years_as_customer, +) +from shop.orders import add_line, new_order, order_summary, order_weight, remove_line +from shop.products import find_products, get_product, price_of, search_products +from shop.sample import CUSTOMERS_CSV, load_demo +from decimal import Decimal + + +class CustomerTests(unittest.TestCase): + def test_load_customers(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual(len(customers), 6) + first = customers[0] + self.assertIsInstance(first, Cust) + self.assertEqual((first.cid, first.name, first.tier, first.country), ("c001", "Anna Becker", "gold", "DE")) + self.assertEqual(first.joined, date(2019, 3, 14)) + self.assertFalse(first.tax_exempt) + + def test_exempt_flag(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual([c.cid for c in customers if c.tax_exempt], ["c005"]) + + def test_blank_lines_and_comments_are_skipped(self): + text = "\n# comment\n\nc9, Zed, z@example.org, , AT, 2022-12-31, 0\n" + customers = load_customers(text) + self.assertEqual(len(customers), 1) + self.assertEqual(customers[0].tier, "bronze") + + def test_bad_join_date_is_rejected(self): + with self.assertRaises(ValueError): + load_customers("c9, Zed, z@example.org, gold, AT, 2022-13-40, 0") + + def test_find_customer(self): + customers = load_customers(CUSTOMERS_CSV) + self.assertEqual(find_customer(customers, "c004").name, "Mira Novak") + self.assertIsNone(find_customer(customers, "c999")) + + def test_group_by_tier(self): + groups = customers_by_tier(load_customers(CUSTOMERS_CSV)) + self.assertEqual(sorted(groups), ["bronze", "gold", "platinum", "silver"]) + self.assertEqual(len(groups["silver"]), 2) + + def test_years_as_customer(self): + c = Cust("c1", "A", "a@example.org", joined=date(2020, 6, 15)) + self.assertEqual(years_as_customer(c, date(2024, 6, 14)), 3) + self.assertEqual(years_as_customer(c, date(2024, 6, 15)), 4) + self.assertEqual(years_as_customer(Cust("c2", "B", "b@example.org"), date(2024, 1, 1)), 0) + + def test_email_validation(self): + self.assertTrue(is_valid_email("a@example.org")) + self.assertFalse(is_valid_email("a@@example.org")) + self.assertFalse(is_valid_email("@example.org")) + self.assertFalse(is_valid_email("a@example.")) + + def test_suggest_tier(self): + self.assertEqual(suggest_tier(Decimal("499.99")), "bronze") + self.assertEqual(suggest_tier(Decimal("500")), "silver") + self.assertEqual(suggest_tier(Decimal("2500")), "gold") + self.assertEqual(suggest_tier(Decimal("9000")), "platinum") + + +class ProductTests(unittest.TestCase): + def test_lookup(self): + self.assertEqual(get_product("P-105").name, "Mechanical keyboard") + self.assertEqual(price_of("P-100"), Decimal("4.50")) + with self.assertRaises(KeyError): + get_product("P-999") + + def test_find_by_category_skips_inactive(self): + self.assertEqual([p.sku for p in find_products("office")], ["P-110"]) + self.assertEqual(len(find_products("electronics")), 3) + + def test_search(self): + self.assertEqual([p.sku for p in search_products("PENS")], ["P-101"]) + self.assertEqual(search_products("fax"), []) + + +class OrderTests(unittest.TestCase): + def test_country_defaults_to_customer_country(self): + order = new_order("T-9", customer(country="FR")) + self.assertEqual(order.ship_country, "FR") + self.assertEqual(order.lines, []) + + def test_adding_same_sku_merges_lines(self): + order = order_with([("P-100", 2)]) + add_line(order, get_product("P-100"), 3) + self.assertEqual(len(order.lines), 1) + self.assertEqual(order.lines[0].qty, 5) + + def test_quantity_must_be_positive(self): + order = order_with([]) + with self.assertRaises(ValueError): + add_line(order, get_product("P-100"), 0) + + def test_remove_line(self): + order = order_with([("P-100", 2), ("P-101", 1)]) + self.assertTrue(remove_line(order, "P-100")) + self.assertFalse(remove_line(order, "P-100")) + self.assertEqual([l.product.sku for l in order.lines], ["P-101"]) + + def test_weight(self): + order = order_with([("P-106", 2), ("P-100", 1)]) + self.assertEqual(order_weight(order), Decimal("5.90")) + + def test_summary_text(self): + _customers, orders, _inv = load_demo() + self.assertEqual(order_summary(orders[0]), "Order O-1001: 2 lines, total 139.74 EUR") + self.assertEqual(order_summary(orders[6]), "Order O-1007: 1 lines, total 27.25 EUR") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_reports_cli.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_reports_cli.py new file mode 100644 index 00000000..86af6c6e --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_reports_cli.py @@ -0,0 +1,175 @@ +import unittest + +from helpers import render, run_cli +from shop import reports +from shop.invoices import build_invoice +from shop.inventory import Inventory +from shop.products import default_catalog +from shop.sample import STOCK, load_demo + +SALES = [ + 'SALES REPORT', + '========================================', + 'O-1001 Anna Becker 139.74', + 'O-1002 Luc Martin 96.88', + 'O-1003 Joe Smith 132.68', + 'O-1004 Mira Novak 96.54', + 'O-1005 Acme GmbH 171.57', + 'O-1006 Sven Berg 105.50', + 'O-1007 Anna Becker 27.25', + 'O-1008 Joe Smith 31.61', + '----------------------------------------', + 'TOTAL 801.77', + '8 orders', + ] + +CUSTOMERS = [ + 'CUSTOMER REPORT', + '========================================', + 'c001 Anna Becker gold 2 orders 160.49', + 'c002 Luc Martin silver 1 orders 82.38', + 'c003 Joe Smith bronze 2 orders 149.79', + 'c004 Mira Novak platinum 1 orders 82.04', + 'c005 Acme GmbH silver 1 orders 171.57', + 'c006 Sven Berg bronze 1 orders 91.00', + ] + +INVENTORY = [ + 'INVENTORY REPORT', + '========================================', + 'P-100 Notebook A5 40', + 'P-101 Ballpoint pens (10) 100', + 'P-102 Desk lamp 8', + 'P-103 USB cable 1m 60', + 'P-104 Wireless mouse 3 LOW', + 'P-105 Mechanical keyboard 6', + 'P-106 Monitor stand 12', + 'P-107 Coffee beans 1kg 25', + 'P-108 Tea sampler 4 LOW', + 'P-109 Office chair 2 LOW', + 'P-110 Whiteboard 90x60 7', + 'P-111 E-book bundle 999', + 'P-112 Fax paper roll 0', + 'stock value 15,066.95', + ] + +TAX = [ + 'TAX SUMMARY', + '========================================', + 'CZ net 68.94 tax 13.10 (19.0%)', + 'DE net 306.44 tax 25.62 (8.4%)', + 'FR net 68.65 tax 13.73 (20.0%)', + 'SE net 72.80 tax 18.20 (25.0%)', + 'US net 139.99 tax 9.80 (7.0%)', + 'ALL net 656.82 tax 80.45', + ] + +AGING = [ + 'AGING REPORT as of 2024-04-10', + '========================================', + 'INV-01001 2024-03-18 139.74 1-30 days', + 'INV-01002 2024-03-19 96.88 1-30 days', + 'INV-01003 2024-03-20 132.68 1-30 days', + 'INV-01004 2024-03-21 96.54 1-30 days', + 'INV-01005 2024-03-22 171.57 1-30 days', + 'INV-01006 2024-03-25 105.50 1-30 days', + 'INV-01007 2024-03-26 27.25 1-30 days', + 'INV-01008 2024-03-29 31.61 1-30 days', + ] + + +class ReportTests(unittest.TestCase): + def setUp(self): + self.customers, self.orders, self.inv = load_demo() + + def test_sales_report(self): + self.assertEqual(render(reports.sales_report, self.orders).splitlines(), SALES) + + def test_customer_report(self): + text = render(reports.customer_report, self.customers, self.orders) + self.assertEqual(text.splitlines(), CUSTOMERS) + + def test_inventory_report(self): + text = render(reports.inventory_report, self.inv, default_catalog()) + self.assertEqual(text.splitlines(), INVENTORY) + + def test_tax_summary(self): + self.assertEqual(render(reports.tax_summary, self.orders).splitlines(), TAX) + + def test_aging_report(self): + invoices = [build_invoice(o) for o in self.orders] + text = render(reports.aging_report, invoices, "2024-04-10") + self.assertEqual(text.splitlines(), AGING) + + def test_aging_buckets(self): + invoices = [build_invoice(o) for o in self.orders[:2]] + early = render(reports.aging_report, invoices, "2024-03-10").splitlines() + self.assertEqual([l.split()[-1] for l in early[2:]], ["current", "current"]) + late = render(reports.aging_report, invoices, "Jun 1, 2024").splitlines() + self.assertEqual([" ".join(l.split()[3:]) for l in late[2:]], ["over 30 days", "over 30 days"]) + + def test_aging_with_unreadable_date(self): + invoices = [build_invoice(o) for o in self.orders[:1]] + text = render(reports.aging_report, invoices, "someday") + self.assertTrue(text.splitlines()[2].endswith("n/a")) + + def test_aging_accepts_day_first_dates(self): + invoices = [build_invoice(o) for o in self.orders[:1]] + text = render(reports.aging_report, invoices, "10/04/2024") + self.assertTrue(text.splitlines()[2].endswith("1-30 days")) + + def test_empty_inventory_report(self): + text = render(reports.inventory_report, Inventory(), default_catalog()[:1]) + self.assertEqual(text.splitlines()[-1], "stock value 0.00") + self.assertEqual(Inventory(STOCK).available("P-111"), 999) + + +class CliTests(unittest.TestCase): + def test_sales_report_output(self): + code, out = run_cli("report", "sales") + self.assertEqual(code, 0) + self.assertEqual(out.splitlines(), SALES) + self.assertTrue(out.endswith("\n")) + self.assertFalse(out.endswith("\n\n")) + + def test_other_reports(self): + self.assertEqual(run_cli("report", "customers")[1].splitlines(), CUSTOMERS) + self.assertEqual(run_cli("report", "inventory")[1].splitlines(), INVENTORY) + self.assertEqual(run_cli("report", "tax")[1].splitlines(), TAX) + + def test_aging_report_output(self): + code, out = run_cli("report", "aging", "2024-04-10") + self.assertEqual(code, 0) + self.assertEqual(out.splitlines(), AGING) + + def test_invoice_command(self): + code, out = run_cli("invoice", "O-1002") + self.assertEqual(code, 0) + self.assertEqual(out.splitlines()[0], "Invoice INV-01002 for Luc Martin") + self.assertEqual(out.splitlines()[-1], " TOTAL 96.88 EUR, due 2024-03-19") + + def test_points_command(self): + self.assertEqual(run_cli("points", "O-1001"), (0, "O-1001 earns 176 points (worth 1.76 EUR)\n")) + + def test_quote_command(self): + code, out = run_cli("quote", "O-1005") + self.assertEqual(out, "Order O-1005: 2 lines, total 171.57 EUR\ndiscount: tier 5.93, coupon 20.00\n") + + def test_confirm_command(self): + code, out = run_cli("confirm", "O-1003") + self.assertEqual(code, 0) + self.assertIn("Total: 132.68 EUR", out) + + def test_errors_do_not_print_to_stdout(self): + self.assertEqual(run_cli("invoice", "O-9999"), (1, "")) + self.assertEqual(run_cli("report", "weather"), (2, "")) + self.assertEqual(run_cli("frobnicate"), (2, "")) + + def test_help(self): + code, out = run_cli() + self.assertEqual(code, 0) + self.assertIn("usage: python -m shop.cli", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_services.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_services.py new file mode 100644 index 00000000..40781ea2 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_services.py @@ -0,0 +1,189 @@ +import unittest +from datetime import date +from decimal import Decimal + +from helpers import order_with +from shop.currency import fmt_money, fmt_pct, money +from shop.customers import load_customers +from shop.inventory import Inventory, OutOfStock, low_stock, reserve_order +from shop.loyalty import points_for_order, redeem_value +from shop.notifications import low_stock_alert, order_confirmation +from shop.returns import can_return, refund_amount +from shop.sample import CUSTOMERS_CSV, STOCK, load_demo +from shop.storage import dump_orders, parse_orders +from shop.validation import ValidationError, ensure_valid, validate_order + + +class CurrencyTests(unittest.TestCase): + def test_money_rounds_half_up(self): + self.assertEqual(money("2.675"), Decimal("2.68")) + self.assertEqual(money(Decimal("0.005")), Decimal("0.01")) + + def test_formatting(self): + self.assertEqual(fmt_money(Decimal("1234567.5")), "1,234,567.50") + self.assertEqual(fmt_pct(Decimal("0.195")), "19.5%") + + +class InventoryTests(unittest.TestCase): + def test_reserve_and_release(self): + inv = Inventory({"P-100": 10}) + inv.reserve("P-100", 4) + self.assertEqual(inv.available("P-100"), 6) + inv.release("P-100", 10) + self.assertEqual(inv.available("P-100"), 10) + + def test_cannot_reserve_more_than_available(self): + inv = Inventory({"P-100": 3}) + with self.assertRaises(OutOfStock): + inv.reserve("P-100", 4) + self.assertEqual(inv.available("P-100"), 3) + + def test_ship_reduces_stock(self): + inv = Inventory({"P-100": 5}) + inv.reserve("P-100", 2) + inv.ship("P-100", 2) + self.assertEqual((inv.stock["P-100"], inv.available("P-100")), (3, 3)) + + def test_low_stock_default_threshold(self): + _c, _o, inv = load_demo() + self.assertEqual(low_stock(inv), ["P-104", "P-108", "P-109"]) + + def test_low_stock_custom_threshold(self): + inv = Inventory(STOCK) + self.assertEqual(low_stock(inv, 3), ["P-104", "P-109"]) + self.assertEqual(low_stock(inv, 0), []) + + def test_reserve_order_is_all_or_nothing(self): + inv = Inventory({"P-100": 5, "P-101": 1}) + order = order_with([("P-100", 2), ("P-101", 2)]) + with self.assertRaises(OutOfStock): + reserve_order(inv, order) + self.assertEqual(inv.available("P-100"), 5) + reserve_order(inv, order_with([("P-100", 2), ("P-101", 1)])) + self.assertEqual(inv.available("P-100"), 3) + + +class LoyaltyTests(unittest.TestCase): + def test_points_follow_tier(self): + _c, orders, _inv = load_demo() + self.assertEqual([points_for_order(o) for o in orders[:3]], [176, 85, 124]) + + def test_points_are_truncated(self): + _c, orders, _inv = load_demo() + self.assertEqual(points_for_order(orders[4]), 214) + + def test_redeem_value(self): + self.assertEqual(redeem_value(176), Decimal("1.76")) + self.assertEqual(redeem_value(0), Decimal("0.00")) + + +class ReturnTests(unittest.TestCase): + def setUp(self): + _c, self.orders, _inv = load_demo() + + def test_window_is_thirty_days(self): + order = self.orders[0] + self.assertTrue(can_return(order, date(2024, 4, 3))) + self.assertFalse(can_return(order, date(2024, 4, 4))) + + def test_cancelled_and_undated_orders_cannot_be_returned(self): + order = order_with([("P-100", 1)], placed_on=None) + self.assertFalse(can_return(order, date(2024, 3, 2))) + dated = order_with([("P-100", 1)]) + dated.status = "cancelled" + self.assertFalse(can_return(dated, date(2024, 3, 2))) + + def test_refund_single_line_order(self): + self.assertEqual(refund_amount(self.orders[6], "P-104", 1), Decimal("18.67")) + + def test_refund_share_of_multi_line_order(self): + self.assertEqual(refund_amount(self.orders[0], "P-100", 6), Decimal("23.74")) + self.assertEqual(refund_amount(self.orders[0], "P-105", 1), Decimal("78.27")) + + def test_refund_errors(self): + with self.assertRaises(KeyError): + refund_amount(self.orders[0], "P-999", 1) + with self.assertRaises(ValueError): + refund_amount(self.orders[0], "P-105", 2) + + +class StorageTests(unittest.TestCase): + def test_parse_demo_orders(self): + _c, orders, _inv = load_demo() + self.assertEqual(len(orders), 8) + self.assertEqual(orders[0].placed_on, date(2024, 3, 4)) + self.assertEqual(orders[1].placed_on, date(2024, 3, 5)) + self.assertEqual([len(o.lines) for o in orders], [2, 2, 1, 2, 2, 2, 1, 2]) + + def test_dump_and_parse_round_trip(self): + customers, orders, _inv = load_demo() + text = dump_orders(orders) + self.assertEqual(text.splitlines()[0], "O-1001;c001;P-100:12,P-105:1;WELCOME10;DE;2024-03-04") + again = parse_orders(text, customers) + self.assertEqual(again, orders) + + def test_unknown_customer(self): + customers = load_customers(CUSTOMERS_CSV) + with self.assertRaises(KeyError): + parse_orders("O-1; c999; P-100:1; ; DE; 2024-03-01", customers) + + def test_bad_order_date(self): + customers = load_customers(CUSTOMERS_CSV) + with self.assertRaises(ValueError): + parse_orders("O-1; c001; P-100:1; ; DE; 31.02.2024", customers) + + def test_both_date_styles(self): + customers = load_customers(CUSTOMERS_CSV) + orders = parse_orders("O-1; c001; P-100:1; ; DE; 3.4.2024\nO-2; c001; P-100:1; ; DE; 2024-04-03", customers) + self.assertEqual(orders[0].placed_on, orders[1].placed_on) + + +class ValidationTests(unittest.TestCase): + def test_valid_order(self): + self.assertEqual(validate_order(order_with([("P-100", 2)])), []) + + def test_empty_order(self): + self.assertEqual(validate_order(order_with([])), ["order has no lines"]) + + def test_quantity_limit(self): + problems = validate_order(order_with([("P-100", 101)])) + self.assertEqual(problems, ["P-100: quantity 101 exceeds 100"]) + self.assertEqual(validate_order(order_with([("P-100", 100)])), []) + + def test_inactive_product_and_country(self): + problems = validate_order(order_with([("P-112", 1)], country="BR")) + self.assertEqual(problems, ["P-112: product is not active", "unknown country: BR"]) + + def test_malformed_coupon(self): + problems = validate_order(order_with([("P-100", 1)], coupon="10-OFF")) + self.assertEqual(problems, ["malformed coupon: 10-OFF"]) + + def test_ensure_valid_raises(self): + with self.assertRaises(ValidationError): + ensure_valid(order_with([])) + ensure_valid(order_with([("P-100", 1)])) + + +class NotificationTests(unittest.TestCase): + def test_confirmation_text(self): + _c, orders, _inv = load_demo() + text = order_confirmation(orders[2]) + self.assertEqual( + text.splitlines(), + [ + "Dear Joe Smith,", + "", + "thank you for your order O-1003.", + " 1x Office chair", + "Total: 132.68 EUR", + "Coupon applied: SAVE5", + ], + ) + + def test_low_stock_alert(self): + self.assertEqual(low_stock_alert([]), "") + self.assertEqual(low_stock_alert(["P-104", "P-109"]), "Low stock: Wireless mouse, Office chair") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_tax_shipping.py b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_tax_shipping.py new file mode 100644 index 00000000..c7bbb973 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/seed/tests/test_tax_shipping.py @@ -0,0 +1,89 @@ +import unittest +from decimal import Decimal + +from helpers import customer, order_with +from shop.sample import load_demo +from shop.shipping import is_free_shipping, shipping_cost +from shop.tax import rate_for, tax_breakdown, tax_for_order + + +class TaxTests(unittest.TestCase): + def test_default_rate(self): + self.assertEqual(rate_for("DE"), Decimal("0.19")) + self.assertEqual(rate_for("BR"), Decimal("0.19")) + + def test_regional_rates(self): + self.assertEqual(rate_for("FR"), Decimal("0.20")) + self.assertEqual(rate_for("US"), Decimal("0.07")) + self.assertEqual(rate_for("CH"), Decimal("0.081")) + + def test_exempt_customer_pays_no_tax(self): + self.assertEqual(rate_for("FR", customer(exempt=True)), Decimal("0")) + self.assertEqual(rate_for("FR", customer()), Decimal("0.20")) + + def test_tax_for_plain_order(self): + self.assertEqual(tax_for_order(order_with([("P-105", 1)])), Decimal("16.91")) + + def test_tax_is_rounded_half_up(self): + order = order_with([("P-105", 1)], country="CH") + self.assertEqual(tax_for_order(order), Decimal("7.21")) + + def test_tax_is_on_discounted_net(self): + _customers, orders, _inv = load_demo() + self.assertEqual(tax_for_order(orders[0]), Decimal("22.31")) + + def test_exempt_order_has_zero_tax(self): + order = order_with([("P-105", 1)], exempt=True) + self.assertEqual(tax_for_order(order), Decimal("0.00")) + + def test_breakdown_per_country(self): + _customers, orders, _inv = load_demo() + self.assertEqual( + tax_breakdown(orders), + { + "DE": Decimal("25.62"), + "FR": Decimal("13.73"), + "US": Decimal("9.80"), + "CZ": Decimal("13.10"), + "SE": Decimal("18.20"), + }, + ) + + +class ShippingTests(unittest.TestCase): + def test_home_country_flat_rate(self): + self.assertEqual(shipping_cost(order_with([("P-103", 1)])), Decimal("6.50")) + + def test_international_surcharge(self): + self.assertEqual(shipping_cost(order_with([("P-103", 1)], country="FR")), Decimal("14.50")) + self.assertEqual(shipping_cost(order_with([("P-103", 1)], country="US")), Decimal("14.50")) + + def test_heavy_parcel_adds_per_kg_fee(self): + order = order_with([("P-106", 2)]) + self.assertEqual(shipping_cost(order), Decimal("7.22")) + + def test_free_shipping_over_threshold(self): + order = order_with([("P-105", 2)]) + self.assertTrue(is_free_shipping(order)) + self.assertEqual(shipping_cost(order), Decimal("0.00")) + + def test_threshold_is_inclusive(self): + order = order_with([("P-101", 5), ("P-111", 7)]) + self.assertTrue(is_free_shipping(order)) + + def test_just_below_threshold_pays(self): + order = order_with([("P-101", 4), ("P-111", 7)]) + self.assertFalse(is_free_shipping(order)) + self.assertEqual(shipping_cost(order), Decimal("6.50")) + + def test_free_shipping_uses_discounted_amount(self): + items = [("P-105", 1), ("P-103", 2)] + self.assertEqual(shipping_cost(order_with(items)), Decimal("0.00")) + self.assertEqual(shipping_cost(order_with(items, tier="gold")), Decimal("6.50")) + + def test_empty_order_ships_nothing(self): + self.assertEqual(shipping_cost(order_with([])), Decimal("0.00")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/refactor-shop/task.md b/scripts/e2e/codex/tasks/refactor-shop/task.md new file mode 100644 index 00000000..c93989b4 --- /dev/null +++ b/scripts/e2e/codex/tasks/refactor-shop/task.md @@ -0,0 +1,35 @@ +--- +id: refactor-shop +title: Refactor a legacy order-processing package (pricing, config, dates, dead code, docs) +kind: refactor +expected_rounds: 30-60 +--- +# refactor-shop + +Notes for the orchestrator (not sent to Codex). + +* Seed: package `shop/` (22 modules, about 1.2k lines), 119 visible unit tests (all green on the seed), `REFACTOR.md` (the 8-step spec), `docs/ARCHITECTURE.md` (old layout). + Reading the whole code base plus the tests is about 25-35k tokens; with the edits and test runs the context grows to roughly 60-100k tokens. +* The work: one new pricing module replacing 4 copies of the price calculation, a frozen `Config` (25 fields, about 15 modules lose constants and gain a `config=None` keyword), rename `Cust` -> `Customer` + (code, tests, docs), 5 report functions return strings and `cli.py` prints them, one `parse_date` replaces 4 hand-written parsers, 5 dead functions removed, type hints/docstrings for the new modules, docs update. +* Acceptance (`accept.py`): runs a pristine copy of the visible tests from `hidden/tests/` with `\bCust\b` -> `Customer` applied (the tests inside the workspace are ignored, so edits to them cannot help), then AST/regex checks for every step + (pricing/config/dates modules and their shape, removed names, no numeric UPPER_CASE constants outside config.py/sample.py, no `quantize`/`print`/`strptime`/`date(...)` where forbidden, hints and docstrings, ARCHITECTURE.md content) + and 12 hidden behaviour checks (`hidden/behaviour.py`): the default values of `Config`, `price_order` golden numbers, edge cases, 400 random orders x random configs against an independent oracle, + `config=` keyword on every function listed in REFACTOR.md step 2, reports returning text without printing, `parse_date` format matrix. +* Typical failure modes of a weak agent: forgetting some modules when moving constants (the constants check names the module), leaving `.quantize` copies behind, `reports` still printing, `Cust` left in docs/tests, + `config=` keyword missing on a function from the list (behaviour checks), `parse_date` not accepting one of the formats. +* Python: written for 3.9 .. 3.14, standard library only, deterministic (the random checks use a fixed seed). +* The reference solution (`reference/overlay/`) is a complete refactor; it passes `accept.py` on Python 3.9 and 3.12. + +## Prompt + +This repository is a small order-processing library (`shop/`) with a unit test suite in `tests/`. I want it cleaned up, and the plan is written down in `REFACTOR.md` in the repository root. Please read that file first and carry out all 8 steps. + +Some things to keep in mind: +- Behaviour must not change. Every number, report line and CLI output has to stay exactly the same. The existing tests are the reference; run them with `python3 -m unittest discover -s tests` after each step and keep them green. You may edit the tests only for the `Cust` -> `Customer` rename. +- There is no pytest and no network here, only the Python 3 standard library. +- Work through the whole code base (`grep` is your friend for finding every place that computes a total, defines a rate or threshold, or parses a date), and remove imports that become unused. +- Update `docs/ARCHITECTURE.md` at the end so it matches the new layout. + +When you are done, reply with a short summary: which modules you added, what you removed, and the final result of the test run. + diff --git a/scripts/e2e/codex/tasks/selftest.py b/scripts/e2e/codex/tasks/selftest.py new file mode 100644 index 00000000..e6d2a3b3 --- /dev/null +++ b/scripts/e2e/codex/tasks/selftest.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Self-test of the task set: accept.py must FAIL on the bare seed, PASS on seed + reference/overlay, and never modify the workspace. + + selftest.py [--vendor DIR] [ID ...] --vendor: directory holding the external seed files (three.module.min.js) +""" +import os +import shutil +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..", "delta")) +import taskfile # noqa: E402 + + +def build(tid, overlay, vendor, dest): + seed = os.path.join(HERE, tid, "seed") + if os.path.isdir(seed): + shutil.copytree(seed, dest) + else: + os.makedirs(dest) + for rel, sha, _n in taskfile.read_task(HERE, tid)["externals"]: + src = os.path.join(vendor or "", rel) + if not os.path.isfile(src) or taskfile.sha256_file(src) != sha: + return "external file %s not available in --vendor" % rel + shutil.copy(src, os.path.join(dest, rel)) + if overlay: + ov = os.path.join(HERE, tid, "reference", "overlay") + for root, _d, files in os.walk(ov): + for n in files: + p = os.path.join(root, n) + t = os.path.join(dest, os.path.relpath(p, ov)) + os.makedirs(os.path.dirname(t), exist_ok=True) + shutil.copy(p, t) + return None + + +def accept(tid, ws): + t0 = time.time() + p = subprocess.run([sys.executable, os.path.join(HERE, tid, "accept.py"), ws], capture_output=True, text=True, timeout=900) + return p.returncode, p.stdout, round(time.time() - t0, 1) + + +def main(): + args = sys.argv[1:] + vendor = None + if args[:1] == ["--vendor"]: + vendor, args = args[1], args[2:] + ids = args or taskfile.task_ids(HERE) + bad = 0 + for tid in ids: + res = [] + for overlay in (False, True): + tmp = tempfile.mkdtemp(prefix="selftest-") + try: + ws = os.path.join(tmp, "ws") + err = build(tid, overlay, vendor, ws) + if err: + res.append("SKIP (%s)" % err) + continue + before = taskfile.workspace_lines(ws) + rc, out, secs = accept(tid, ws) + after = taskfile.workspace_lines(ws) + same = before == after + ok = (rc != 0) if not overlay else (rc == 0) + res.append("%s rc=%d %.1fs%s" % ("ok" if ok else "WRONG", rc, secs, "" if same else " WORKSPACE MODIFIED")) + if not ok or not same: + bad += 1 + print(out[-1500:]) + finally: + shutil.rmtree(tmp, ignore_errors=True) + print("%-18s seed: %-28s seed+overlay: %s" % (tid, res[0], res[1])) + print("selftest: %s" % ("FAILED" if bad else "all good")) + sys.exit(1 if bad else 0) + + +main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/accept.py b/scripts/e2e/codex/tasks/smoke-mini/accept.py new file mode 100644 index 00000000..410964d6 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/accept.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Acceptance check for task smoke-mini. + +Usage: python3 accept.py WORKSPACE +Exit 0 when the task is done; any other exit code means not done. The workspace is never modified: everything runs in a temporary copy. +""" + +import hashlib +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PRISTINE = HERE / "hidden" / "pristine_tests" +HIDDEN_TESTS = HERE / "hidden" / "test_hidden.py" +IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".git") + +failed = [] + + +def check(name, ok, detail=""): + if ok: + print("PASS " + name) + else: + print("FAIL %s :: %s" % (name, detail.strip()[-1500:])) + failed.append(name) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def run_unittest(cwd, start_dir, timeout=100): + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0") + try: + proc = subprocess.run( + [sys.executable, "-m", "unittest", "discover", "-s", start_dir], + cwd=str(cwd), env=env, capture_output=True, text=True, timeout=timeout, + ) + except subprocess.TimeoutExpired: + return False, "timeout" + return proc.returncode == 0, proc.stdout + proc.stderr + + +def main(): + if len(sys.argv) != 2: + print("usage: accept.py WORKSPACE") + return 2 + workspace = Path(sys.argv[1]).resolve() + if not workspace.is_dir(): + print("FAIL workspace :: not a directory") + return 2 + + # 1. the pristine tests must be untouched + for src in sorted(PRISTINE.rglob("*")): + if not src.is_file() or "__pycache__" in src.parts: + continue + rel = src.relative_to(PRISTINE) + target = workspace / "tests" / rel + same = target.is_file() and digest(target) == digest(src) + check("tests-untouched:" + rel.as_posix(), same, "tests/%s is missing or was modified" % rel.as_posix()) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) / "ws" + shutil.copytree(workspace, work, ignore=IGNORE) + # run the pristine tests, not whatever is in tests/ now + shutil.rmtree(work / "tests", ignore_errors=True) + shutil.copytree(PRISTINE, work / "tests", ignore=IGNORE) + ok, out = run_unittest(work, "tests") + check("visible-tests", ok, out) + + hidden_dir = work / "_hidden" + hidden_dir.mkdir() + shutil.copy(HIDDEN_TESTS, hidden_dir / "test_hidden.py") + ok, out = run_unittest(work, "_hidden") + check("hidden-tests", ok, out) + + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_casing_stats.py b/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_casing_stats.py new file mode 100644 index 00000000..6ac2ccb0 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_casing_stats.py @@ -0,0 +1,26 @@ +import unittest + +from textkit import snake_case, title_case, top_words, word_frequencies + + +class CasingTests(unittest.TestCase): + def test_title_case_keeps_small_words(self): + self.assertEqual(title_case("the lord of the rings"), "The Lord of the Rings") + + def test_snake_case_from_camel(self): + self.assertEqual(snake_case("parseHttpResponse"), "parse_http_response") + + def test_snake_case_from_kebab(self): + self.assertEqual(snake_case("Some-Mixed words_here"), "some_mixed_words_here") + + +class StatsTests(unittest.TestCase): + def test_frequencies(self): + self.assertEqual(word_frequencies("It is, it IS!"), {"it": 2, "is": 2}) + + def test_top_words_tie_order(self): + self.assertEqual(top_words("b a b a c", 2), [("a", 2), ("b", 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_words.py b/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_words.py new file mode 100644 index 00000000..ec618b94 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_words.py @@ -0,0 +1,25 @@ +import unittest + +from textkit import count_words, truncate_words + + +class WordsTests(unittest.TestCase): + def test_count_words(self): + self.assertEqual(count_words("one two three\nfour"), 4) + + def test_count_empty(self): + self.assertEqual(count_words(" "), 0) + + def test_short_text_unchanged(self): + self.assertEqual(truncate_words("one two three", 3), "one two three") + + def test_truncates_and_adds_suffix(self): + self.assertEqual(truncate_words("one two three four five", 3), "one two three...") + + def test_invalid_limit(self): + with self.assertRaises(ValueError): + truncate_words("one", 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_wrap.py b/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_wrap.py new file mode 100644 index 00000000..6d566e5b --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/hidden/pristine_tests/test_wrap.py @@ -0,0 +1,34 @@ +import unittest + +from textkit import wrap_text + + +class WrapTextTests(unittest.TestCase): + def test_short_text_is_one_line(self): + self.assertEqual(wrap_text("hello world", 20), ["hello world"]) + + def test_exact_width_fits(self): + self.assertEqual(wrap_text("abc def", 7), ["abc def"]) + + def test_breaks_between_words(self): + self.assertEqual(wrap_text("the quick brown fox", 10), ["the quick", "brown fox"]) + + def test_collapses_whitespace(self): + self.assertEqual(wrap_text("a b\n c", 10), ["a b c"]) + + def test_empty_text(self): + self.assertEqual(wrap_text("", 5), []) + + def test_long_word_is_split(self): + self.assertEqual(wrap_text("abcdefghij", 4), ["abcd", "efgh", "ij"]) + + def test_long_word_between_words(self): + self.assertEqual(wrap_text("go extraordinary now", 6), ["go", "extrao", "rdinar", "y now"]) + + def test_invalid_width(self): + with self.assertRaises(ValueError): + wrap_text("x", 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/hidden/test_hidden.py b/scripts/e2e/codex/tasks/smoke-mini/hidden/test_hidden.py new file mode 100644 index 00000000..5e178ed8 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/hidden/test_hidden.py @@ -0,0 +1,75 @@ +import unittest + +from textkit import ( + count_words, + snake_case, + title_case, + top_words, + truncate_words, + word_frequencies, + wrap_text, +) + + +class HiddenWrap(unittest.TestCase): + def test_long_word_exact_multiple(self): + self.assertEqual(wrap_text("abcdefgh", 4), ["abcd", "efgh"]) + + def test_width_one(self): + self.assertEqual(wrap_text("ab c", 1), ["a", "b", "c"]) + + def test_long_word_no_characters_lost(self): + word = "supercalifragilisticexpialidocious" + for width in range(1, 12): + lines = wrap_text(word, width) + self.assertEqual("".join(lines), word, width) + self.assertTrue(all(len(line) <= width for line in lines), width) + + def test_long_word_tail_joins_next_word(self): + self.assertEqual(wrap_text("abcdefg hi", 5), ["abcde", "fg hi"]) + + def test_text_is_preserved_word_for_word(self): + text = "pack my box with five dozen liquor jugs and then some more words to wrap" + for width in (6, 8, 13, 40): + lines = wrap_text(text, width) + self.assertEqual(" ".join(lines).split(), text.split(), width) + self.assertTrue(all(len(line) <= width for line in lines), width) + + +class HiddenWords(unittest.TestCase): + def test_limit_one(self): + self.assertEqual(truncate_words("alpha beta gamma", 1), "alpha...") + + def test_custom_suffix(self): + self.assertEqual(truncate_words("a b c d e f", 4, suffix=" [more]"), "a b c d [more]") + + def test_empty_suffix(self): + self.assertEqual(truncate_words("a b c d", 2, suffix=""), "a b") + + def test_exactly_at_limit(self): + self.assertEqual(truncate_words(" a b ", 2), "a b") + + def test_one_over_limit(self): + self.assertEqual(truncate_words("a b c", 2), "a b...") + + def test_empty_text(self): + self.assertEqual(truncate_words("", 3), "") + + +class HiddenUnchanged(unittest.TestCase): + def test_count_words(self): + self.assertEqual(count_words("a\tb\nc "), 3) + + def test_title_case(self): + self.assertEqual(title_case("war and PEACE"), "War and Peace") + + def test_snake_case(self): + self.assertEqual(snake_case("HTTPServer error-code"), "httpserver_error_code") + + def test_stats(self): + self.assertEqual(word_frequencies("a A b"), {"a": 2, "b": 1}) + self.assertEqual(top_words("x y y z z z", 2), [("z", 3), ("y", 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/words.py b/scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/words.py new file mode 100644 index 00000000..77e9c18e --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/words.py @@ -0,0 +1,23 @@ +"""Word counting and truncation.""" + +from __future__ import annotations + + +def count_words(text: str) -> int: + """Number of whitespace separated words in ``text``.""" + return len(text.split()) + + +def truncate_words(text: str, limit: int, suffix: str = "...") -> str: + """Keep the first ``limit`` words of ``text``. + + If words were dropped, ``suffix`` is appended directly after the last kept + word. Text with ``limit`` words or fewer is returned with normalised + spacing and no suffix. + """ + if limit < 1: + raise ValueError("limit must be at least 1") + words = text.split() + if len(words) <= limit: + return " ".join(words) + return " ".join(words[:limit]) + suffix diff --git a/scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/wrap.py b/scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/wrap.py new file mode 100644 index 00000000..92d59203 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/reference/overlay/textkit/wrap.py @@ -0,0 +1,36 @@ +"""Greedy word wrapping.""" + +from __future__ import annotations + +from typing import List + + +def _chunks(word: str, width: int) -> List[str]: + """Break a single word into pieces of at most ``width`` characters.""" + if len(word) <= width: + return [word] + return [word[i:i + width] for i in range(0, len(word), width)] + + +def wrap_text(text: str, width: int) -> List[str]: + """Wrap ``text`` into lines of at most ``width`` characters. + + Whitespace runs collapse to a single space. Words longer than ``width`` + are split into pieces that fill whole lines. + """ + if width < 1: + raise ValueError("width must be at least 1") + lines: List[str] = [] + current = "" + for word in text.split(): + for piece in _chunks(word, width): + if not current: + current = piece + elif len(current) + 1 + len(piece) <= width: + current += " " + piece + else: + lines.append(current) + current = piece + if current: + lines.append(current) + return lines diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_casing_stats.py b/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_casing_stats.py new file mode 100644 index 00000000..6ac2ccb0 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_casing_stats.py @@ -0,0 +1,26 @@ +import unittest + +from textkit import snake_case, title_case, top_words, word_frequencies + + +class CasingTests(unittest.TestCase): + def test_title_case_keeps_small_words(self): + self.assertEqual(title_case("the lord of the rings"), "The Lord of the Rings") + + def test_snake_case_from_camel(self): + self.assertEqual(snake_case("parseHttpResponse"), "parse_http_response") + + def test_snake_case_from_kebab(self): + self.assertEqual(snake_case("Some-Mixed words_here"), "some_mixed_words_here") + + +class StatsTests(unittest.TestCase): + def test_frequencies(self): + self.assertEqual(word_frequencies("It is, it IS!"), {"it": 2, "is": 2}) + + def test_top_words_tie_order(self): + self.assertEqual(top_words("b a b a c", 2), [("a", 2), ("b", 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_words.py b/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_words.py new file mode 100644 index 00000000..ec618b94 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_words.py @@ -0,0 +1,25 @@ +import unittest + +from textkit import count_words, truncate_words + + +class WordsTests(unittest.TestCase): + def test_count_words(self): + self.assertEqual(count_words("one two three\nfour"), 4) + + def test_count_empty(self): + self.assertEqual(count_words(" "), 0) + + def test_short_text_unchanged(self): + self.assertEqual(truncate_words("one two three", 3), "one two three") + + def test_truncates_and_adds_suffix(self): + self.assertEqual(truncate_words("one two three four five", 3), "one two three...") + + def test_invalid_limit(self): + with self.assertRaises(ValueError): + truncate_words("one", 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_wrap.py b/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_wrap.py new file mode 100644 index 00000000..6d566e5b --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/tests/test_wrap.py @@ -0,0 +1,34 @@ +import unittest + +from textkit import wrap_text + + +class WrapTextTests(unittest.TestCase): + def test_short_text_is_one_line(self): + self.assertEqual(wrap_text("hello world", 20), ["hello world"]) + + def test_exact_width_fits(self): + self.assertEqual(wrap_text("abc def", 7), ["abc def"]) + + def test_breaks_between_words(self): + self.assertEqual(wrap_text("the quick brown fox", 10), ["the quick", "brown fox"]) + + def test_collapses_whitespace(self): + self.assertEqual(wrap_text("a b\n c", 10), ["a b c"]) + + def test_empty_text(self): + self.assertEqual(wrap_text("", 5), []) + + def test_long_word_is_split(self): + self.assertEqual(wrap_text("abcdefghij", 4), ["abcd", "efgh", "ij"]) + + def test_long_word_between_words(self): + self.assertEqual(wrap_text("go extraordinary now", 6), ["go", "extrao", "rdinar", "y now"]) + + def test_invalid_width(self): + with self.assertRaises(ValueError): + wrap_text("x", 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/__init__.py b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/__init__.py new file mode 100644 index 00000000..26952e96 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/__init__.py @@ -0,0 +1,16 @@ +"""textkit: small helpers for wrapping, truncating and counting text.""" + +from .casing import snake_case, title_case +from .stats import top_words, word_frequencies +from .words import count_words, truncate_words +from .wrap import wrap_text + +__all__ = [ + "count_words", + "snake_case", + "title_case", + "top_words", + "truncate_words", + "word_frequencies", + "wrap_text", +] diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/casing.py b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/casing.py new file mode 100644 index 00000000..c640e32f --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/casing.py @@ -0,0 +1,25 @@ +"""Case conversion helpers.""" + +from __future__ import annotations + +import re + +_SMALL_WORDS = {"a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to"} + + +def title_case(text: str) -> str: + """Capitalise each word except short function words (the first word is always capitalised).""" + out = [] + for index, word in enumerate(text.split()): + if index > 0 and word.lower() in _SMALL_WORDS: + out.append(word.lower()) + else: + out.append(word[:1].upper() + word[1:].lower()) + return " ".join(out) + + +def snake_case(text: str) -> str: + """Convert words, camelCase or kebab-case text to snake_case.""" + text = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", text) + parts = re.split(r"[\s\-_]+", text.strip()) + return "_".join(p.lower() for p in parts if p) diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/stats.py b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/stats.py new file mode 100644 index 00000000..804fdcb4 --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/stats.py @@ -0,0 +1,21 @@ +"""Word statistics.""" + +from __future__ import annotations + +import re +from typing import Dict, List, Tuple + + +def word_frequencies(text: str) -> Dict[str, int]: + """Count lower-cased words (letters, digits and apostrophes only).""" + counts: Dict[str, int] = {} + for word in re.findall(r"[A-Za-z0-9']+", text.lower()): + counts[word] = counts.get(word, 0) + 1 + return counts + + +def top_words(text: str, n: int = 3) -> List[Tuple[str, int]]: + """The ``n`` most frequent words; ties are ordered alphabetically.""" + counts = word_frequencies(text) + ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0])) + return ranked[:n] diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/words.py b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/words.py new file mode 100644 index 00000000..95c56dbf --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/words.py @@ -0,0 +1,23 @@ +"""Word counting and truncation.""" + +from __future__ import annotations + + +def count_words(text: str) -> int: + """Number of whitespace separated words in ``text``.""" + return len(text.split()) + + +def truncate_words(text: str, limit: int, suffix: str = "...") -> str: + """Keep the first ``limit`` words of ``text``. + + If words were dropped, ``suffix`` is appended directly after the last kept + word. Text with ``limit`` words or fewer is returned with normalised + spacing and no suffix. + """ + if limit < 1: + raise ValueError("limit must be at least 1") + words = text.split() + if len(words) <= limit: + return " ".join(words) + return " ".join(words[:limit - 1]) + suffix diff --git a/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/wrap.py b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/wrap.py new file mode 100644 index 00000000..7aed3baf --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/seed/textkit/wrap.py @@ -0,0 +1,36 @@ +"""Greedy word wrapping.""" + +from __future__ import annotations + +from typing import List + + +def _chunks(word: str, width: int) -> List[str]: + """Break a single word into pieces of at most ``width`` characters.""" + if len(word) <= width: + return [word] + return [word[i:i + width - 1] for i in range(0, len(word), width)] + + +def wrap_text(text: str, width: int) -> List[str]: + """Wrap ``text`` into lines of at most ``width`` characters. + + Whitespace runs collapse to a single space. Words longer than ``width`` + are split into pieces that fill whole lines. + """ + if width < 1: + raise ValueError("width must be at least 1") + lines: List[str] = [] + current = "" + for word in text.split(): + for piece in _chunks(word, width): + if not current: + current = piece + elif len(current) + 1 + len(piece) <= width: + current += " " + piece + else: + lines.append(current) + current = piece + if current: + lines.append(current) + return lines diff --git a/scripts/e2e/codex/tasks/smoke-mini/task.md b/scripts/e2e/codex/tasks/smoke-mini/task.md new file mode 100644 index 00000000..f687f4bb --- /dev/null +++ b/scripts/e2e/codex/tasks/smoke-mini/task.md @@ -0,0 +1,20 @@ +--- +id: smoke-mini +title: Fix two bugs in the textkit package +kind: bugfix +expected_rounds: 6-14 +--- +# Fix two bugs in the textkit package + +Pipeline smoke test only; not part of the measured task set. Small package `textkit/` (about 130 lines, 4 modules) with 2 seeded bugs +(`wrap._chunks` slices one character too few; `words.truncate_words` keeps `limit - 1` words). 18 visible tests, 3 fail on the seed. +Acceptance (`accept.py`): the pristine `tests/` files are byte-identical, the pristine tests pass, and `hidden/test_hidden.py` (15 extra cases) passes. + +## Prompt + +This repository contains a small Python package, `textkit/`, with unit tests in `tests/`. Some of the tests currently fail. Please find the cause in the package code and fix it so that all tests pass. Do not edit anything under `tests/`; the tests describe the intended behaviour. + +Run the tests with `python3 -m unittest discover -s tests`. + +When you are done, reply with a short summary of what was wrong and what you changed. + diff --git a/scripts/e2e/codex/tasks/ttt/accept.py b/scripts/e2e/codex/tasks/ttt/accept.py new file mode 100644 index 00000000..2c0c0692 --- /dev/null +++ b/scripts/e2e/codex/tasks/ttt/accept.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Static acceptance for the Three.js tic-tac-toe task (no browser on the server). + + accept.py WORKSPACE exit 0 = every check passed + +The six real-mouse browser checks (scripts/e2e/codex/check_ttt.mjs) need Node + Playwright and run afterwards over the stored workspaces. +This script only reads the workspace. +""" +import hashlib +import os +import re +import sys + +ws = os.path.abspath(sys.argv[1]) +results = [] + + +def check(name, ok, detail=""): + results.append(bool(ok)) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else " :: " + str(detail)[:300]), flush=True) + + +THREE_SHA = "08fd7545d13d2c7fb65ab691530a802dafefd638596501854f267d0fb13c39e7" +path = os.path.join(ws, "index.html") +check("index.html exists", os.path.isfile(path)) +html = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" +check("index.html is not trivial (>= 1500 bytes)", len(html.encode()) >= 1500, len(html)) +three = os.path.join(ws, "three.module.min.js") +check("vendored three.module.min.js still present and unmodified", + os.path.isfile(three) and hashlib.sha256(open(three, "rb").read()).hexdigest() == THREE_SHA) +check("imports the vendored build by a relative path", re.search(r"""from\s+['"](\./)?three\.module\.min\.js['"]""", html) or + re.search(r"""import\(\s*['"](\./)?three\.module\.min\.js['"]""", html)) +check("loads nothing from the network", not re.search(r"""(src|href)\s*=\s*['"]https?://""", html) and not re.search(r"""(from|import)\s*\(?\s*['"]https?://""", html)) +check("uses a WebGL renderer", "WebGLRenderer" in html) +check("creates at least two kinds of 3D meshes (X and O)", len(re.findall(r"\bMesh\s*\(", html)) >= 2) +check("raycasting for clicks", "Raycaster" in html and "setFromCamera" in html) +check("click or pointer listener", re.search(r"""addEventListener\(\s*['"](click|pointerdown|mousedown|pointerup|mouseup)['"]""", html) or re.search(r"\bon(click|pointerdown|mousedown)\s*=", html)) +check('element with id="status"', re.search(r"""id\s*=\s*['"]status['"]""", html) or "getElementById('status')" in html or 'getElementById("status")' in html) +check('button with id="restart"', re.search(r"""]*id\s*=\s*['"]restart['"]""", html) or re.search(r"""id\s*=\s*['"]restart['"]""", html)) +check("win and draw logic present", re.search(r"win", html, re.I) and re.search(r"draw", html, re.I) and + (len(re.findall(r"\[\s*\d\s*,\s*\d\s*,\s*\d\s*\]", html)) >= 8 or re.search(r"for\s*\(", html))) +check("status strings", re.search(r"turn", html, re.I) and re.search(r"wins", html, re.I)) +script = "\n".join(re.findall(r"]*>(.*?)", html, re.S)) +check("inline script present, brackets balanced", script.strip() != "" and all(script.count(a) == script.count(b) for a, b in ("()", "[]", "{}")), + "%d/%d %d/%d %d/%d" % (script.count("("), script.count(")"), script.count("["), script.count("]"), script.count("{"), script.count("}"))) +print("SUMMARY %d/%d" % (sum(results), len(results))) +sys.exit(0 if all(results) else 1) diff --git a/scripts/e2e/codex/tasks/ttt/hidden/check_ttt.mjs b/scripts/e2e/codex/tasks/ttt/hidden/check_ttt.mjs new file mode 100644 index 00000000..742c979c --- /dev/null +++ b/scripts/e2e/codex/tasks/ttt/hidden/check_ttt.mjs @@ -0,0 +1,112 @@ +// Shared browser checks for the Three.js tic-tac-toe game (offline test driver, not shipped): 6 checks, real mouse clicks. +// node check_ttt.mjs /path/to/index.html (needs `playwright` + its chromium installed in the test directory only) +import { chromium } from 'playwright'; +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { resolve, dirname, basename, extname, join } from 'node:path'; + +const file = resolve(process.argv[2] ?? 'index.html'); +// ES module imports are blocked on file:// (CORS), so the game's directory is served over local http, as any real deployment would. +const types = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png' }; +const root = dirname(file); +const server = createServer(async (req, res) => { + try { + const path = decodeURIComponent(new URL(req.url, 'http://x').pathname); + const target = path === '/' ? file : join(root, path); + if (!target.startsWith(root)) { res.writeHead(403).end(); return; } + const body = await readFile(target); + res.writeHead(200, { 'content-type': types[extname(target)] ?? 'application/octet-stream' }).end(body); + } catch { res.writeHead(404).end(); } +}); +await new Promise((ok) => server.listen(0, '127.0.0.1', ok)); +const url = `http://127.0.0.1:${server.address().port}/${basename(file)}`; +const results = []; +const check = (name, ok, detail = '') => { + results.push({ name, ok: !!ok, detail }); + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${ok ? '' : ' :: ' + detail}`); +}; + +const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] }); +const page = await browser.newPage({ viewport: { width: 900, height: 900 } }); +const errors = []; +page.on('pageerror', (e) => errors.push(String(e))); +page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); }); +await page.goto(url); +await page.waitForTimeout(1500); + +check('1 loads without page error', errors.length === 0, errors.join(' | ').slice(0, 300)); +const box = await page.evaluate(() => { + const c = document.querySelector('canvas'); + if (!c) return null; + const r = c.getBoundingClientRect(); + return { x: r.x, y: r.y, w: r.width, h: r.height }; +}); +check('2 visible WebGL canvas', box && box.w > 100 && box.h > 100, JSON.stringify(box)); + +const status = async () => (await page.evaluate(() => document.getElementById('status')?.textContent ?? '')).trim(); +const restart = async () => { const b = await page.$('#restart'); if (b) await b.click(); await page.waitForTimeout(200); }; +// The board layout is the game's own (camera, perspective, size): find the nine cells by probing. Click a dense grid over the +// canvas; a point that changes the status text placed a mark (then restart). The accepted points form nine clusters. +const initial = await status(); +const accepted = []; +const N = 28; +for (let gy = 0; gy < N; gy++) { + for (let gx = 0; gx < N; gx++) { + const x = box.x + (gx + 0.5) * box.w / N, y = box.y + (gy + 0.5) * box.h / N; + await page.mouse.click(x, y); + await page.waitForTimeout(40); + if ((await status()) !== initial) { accepted.push([x, y]); await restart(); } + } +} +let pts = []; +if (accepted.length >= 9) { + // Rows are thirds of the accepted y-range, columns thirds of that row's x-range; each cell is the accepted point nearest to the third's centre. + const ys = accepted.map((p) => p[1]); + const y0 = Math.min(...ys), y1 = Math.max(...ys); + for (let r = 0; r < 3; r++) { + const lo = y0 + (r * (y1 - y0 + 1)) / 3, hi = y0 + ((r + 1) * (y1 - y0 + 1)) / 3; + const band = accepted.filter((p) => p[1] >= lo && p[1] < hi); + if (!band.length) continue; + const x0 = Math.min(...band.map((p) => p[0])), x1 = Math.max(...band.map((p) => p[0])); + const cy = band.reduce((a, p) => a + p[1], 0) / band.length; + for (let c = 0; c < 3; c++) { + const cx = x0 + ((c + 0.5) * (x1 - x0 + 1)) / 3; + pts.push(band.reduce((best, p) => (Math.hypot(p[0] - cx, p[1] - cy) < Math.hypot(best[0] - cx, best[1] - cy) ? p : best), band[0])); + } + } +} +console.log(`probe: ${accepted.length} accepted clicks, ${pts.length} cell centres`); +if (pts.length !== 9) { + check('3 row win via real clicks', false, 'could not find nine clickable cells'); + check('4 moves blocked after the win', false, 'no cells'); + check('5 restart to empty board (X to move)', false, 'no cells'); + check('6 draw via real clicks', false, 'no cells'); + await browser.close(); server.close(); + console.log('SUMMARY ' + results.filter((r) => r.ok).length + '/6'); + process.exit(1); +} +const click = async (i) => { await page.mouse.click(pts[i][0], pts[i][1]); await page.waitForTimeout(Number(process.env.CLICK_WAIT_MS ?? 250)); }; + +// 3: row win via real clicks: X takes 0,1,2; O takes 3,4 +for (const i of [0, 3, 1, 4, 2]) await click(i); +const s3 = await status(); +check('3 row win via real clicks', /X/i.test(s3) && /win/i.test(s3), s3); +// 4: moves blocked after the win +const before = await status(); +await click(5); await click(6); +const after = await status(); +check('4 moves blocked after the win', before === after && /win/i.test(after), `${before} -> ${after}`); +// 5: restart to an empty board +await restart(); +const s5 = await status(); +check('5 restart to empty board (X to move)', /X/i.test(s5) && !/win|draw/i.test(s5), s5); +// 6: draw via real clicks: X O X / X O O / O X X +for (const i of [0, 1, 2, 4, 3, 5, 7, 6, 8]) { await click(i); if (process.env.TRACE) console.log(" click", i, "->", await status()); } +const s6 = await status(); +check('6 draw via real clicks', /draw/i.test(s6), s6); + +await browser.close(); +server.close(); +const passed = results.filter((r) => r.ok).length; +console.log(`SUMMARY ${passed}/6`); +process.exit(passed === 6 ? 0 : 1); diff --git a/scripts/e2e/codex/tasks/ttt/reference/overlay/index.html b/scripts/e2e/codex/tasks/ttt/reference/overlay/index.html new file mode 100644 index 00000000..51f1a93e --- /dev/null +++ b/scripts/e2e/codex/tasks/ttt/reference/overlay/index.html @@ -0,0 +1,402 @@ + + + + + +Tic-Tac-Toe 3D + + + +
      +
      +

      X's turn

      + +
      +

      Click a square to place a mark. X moves first.

      + + + + diff --git a/scripts/e2e/codex/tasks/ttt/task.md b/scripts/e2e/codex/tasks/ttt/task.md new file mode 100644 index 00000000..ba36677f --- /dev/null +++ b/scripts/e2e/codex/tasks/ttt/task.md @@ -0,0 +1,28 @@ +--- +id: ttt +title: Three.js tic-tac-toe in one file +kind: create +expected_rounds: 15-60 +--- +# Three.js tic-tac-toe in one file + +Existing task of docs/e2e-run.md (jobs 943*), prompt text unchanged from `scripts/e2e/codex/prompt-threejs.txt` (sha256 f57248412f69b4a6a76aab00c2ff33ee3ce676849768f847d412c7e9e9d8a074 of the file; the file ends with a newline that `$(cat file)` stripped, the extracted prompt is the same string). +The vendored three.module.min.js is an external seed file (third-party, not in Git). +Acceptance on the server is STATIC (`accept.py`: file present, imports the vendored module by a relative path, no network URL, WebGL renderer, raycaster, #status, #restart, win/draw logic, click handler, and the page's script is syntactically plausible). The six real-mouse browser checks of `scripts/e2e/codex/check_ttt.mjs` need Node + Playwright, which the server does not have; they run afterwards on a machine that has them over the stored workspaces (`delta/browser_check_ttt.sh`) and are reported separately. + +## Prompt + +Build a complete tic-tac-toe game as a single self-contained file named index.html in the current directory, using Three.js (WebGL) for all rendering. A vendored build of Three.js is already in this directory as three.module.min.js; import it with a relative path and do not load anything from the network. + +Requirements: +- A 3x3 board drawn in 3D with a visible WebGL canvas that fills the page; X and O are distinct 3D meshes; use real mouse clicks on the canvas (raycasting) to place marks. Two players alternate, X first. +- Detect a win (rows, columns, diagonals) and a draw. Show the status ("X's turn", "O wins", "Draw") in an element with id="status". +- After a win or a draw, further clicks on the board must not place marks. +- A button with id="restart" resets the board to empty and X to move. +- The page must load without any JavaScript error. + +Verify your work before finishing: serve or open the file, and write and run a small automated check (for example with Node or Python) if the tools are available. When you are done, reply with a short summary of what you built and how you verified it. + + +## External seed files +three.module.min.js 08fd7545d13d2c7fb65ab691530a802dafefd638596501854f267d0fb13c39e7 691648 From 5629dd0b39bd8584d0e93d65c90b393fe38cb1c7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 30 Oct 2026 23:32:57 +0100 Subject: [PATCH 02/10] e2e codex-delta: copy seeds with writable permissions Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/codex/delta/cell.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/scripts/e2e/codex/delta/cell.py b/scripts/e2e/codex/delta/cell.py index 300a03e9..7eb65375 100644 --- a/scripts/e2e/codex/delta/cell.py +++ b/scripts/e2e/codex/delta/cell.py @@ -33,6 +33,17 @@ def utc(): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +def copy_tree(src, dst): + """Copy a tree byte for byte with default (writable) permissions: the task files on the server are read-only.""" + os.makedirs(dst, exist_ok=True) + for root, dirs, files in os.walk(src): + rel = os.path.relpath(root, src) + for d in dirs: + os.makedirs(os.path.join(dst, rel, d) if rel != "." else os.path.join(dst, d), exist_ok=True) + for n in files: + shutil.copyfile(os.path.join(root, n), os.path.join(dst, rel, n) if rel != "." else os.path.join(dst, n)) + + def free_port(): with socket.socket() as s: s.bind(("127.0.0.1", 0)) @@ -81,7 +92,7 @@ def main(): os.makedirs(active, exist_ok=True) seed = os.path.join(tdir, "seed") if os.path.isdir(seed): - shutil.copytree(seed, ws) + copy_tree(seed, ws) else: os.makedirs(ws) for rel, sha, _n in meta["externals"]: @@ -90,7 +101,7 @@ def main(): print("refusing: external seed file %s missing or differs (%s)" % (rel, src), file=sys.stderr) shutil.rmtree(ws, ignore_errors=True) return 3 - shutil.copy(src, os.path.join(ws, rel)) + shutil.copyfile(src, os.path.join(ws, rel)) want = [l for l in open(os.path.join(a.tasks_root, "MANIFEST.sha256")).read().splitlines() if l.startswith("SEEDTREE %s " % a.task)] have = taskfile.tree_digest(taskfile.workspace_lines(ws)) if not want or want[0].split()[2] != have: From b17fe85a9eb782fd0f556cf641fc1f7ea3cfa41b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 30 Oct 2026 23:34:24 +0100 Subject: [PATCH 03/10] e2e codex-delta: stack.json after the variant env, prefill share line Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/codex/delta/block.py | 3 ++- scripts/e2e/codex/delta/block.sh | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/e2e/codex/delta/block.py b/scripts/e2e/codex/delta/block.py index 79af6731..f76fa140 100644 --- a/scripts/e2e/codex/delta/block.py +++ b/scripts/e2e/codex/delta/block.py @@ -79,7 +79,8 @@ def main(): log = read_log(a.engine_log) on_lines = [l for l in log.splitlines() if SKIP_ON.search(l)] off_lines = [l for l in log.splitlines() if SKIP_OFF_OURS.search(l)] - skip_state = {"expect": a.expect_skip, "on_lines": on_lines[:3], "off_lines": off_lines[:3]} + skip_state = {"expect": a.expect_skip, "on_lines": on_lines[:3], "off_lines": off_lines[:3], + "prefill_cpu_share_lines": [l.strip()[:300] for l in log.splitlines() if "CPU share" in l][:3]} ok = bool(on_lines) if a.expect_skip == "on" else not on_lines say("route tail skip check expect=%s: %s" % (a.expect_skip, "OK" if ok else "MISMATCH")) for l in (on_lines + off_lines)[:3]: diff --git a/scripts/e2e/codex/delta/block.sh b/scripts/e2e/codex/delta/block.sh index 05986a8c..8e678362 100644 --- a/scripts/e2e/codex/delta/block.sh +++ b/scripts/e2e/codex/delta/block.sh @@ -50,6 +50,7 @@ if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then l ( while sleep 10; do echo "$(date +%T) $(grep -E "MemAvailable|Shmem:|Dirty" /proc/meminfo | tr -s ' ' | tr '\n' ' ') $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory)"; done >>"$STACK/memsample.txt" 2>/dev/null ) & SAMP=$! COMMON="--variant $V --tag $TAG --cells \"$CELLS\" --runs-root $RUNS --tasks-root $TASKS --stack-dir $STACK --codex-bin $CODEX --wall-limit $WALL --max-rounds $CAP --active-dir $ROOT/_active" +write_stack_json() { python3 - "$STACK/stack.json" "$V" "$KIND" <<'PY' import json, sys, subprocess, os d = {"variant": sys.argv[2], "kind": sys.argv[3], "host": os.uname().nodename, "kernel": os.uname().release, "env": {}} @@ -60,6 +61,7 @@ d["gpu"] = subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version,memory d["codex_version"] = subprocess.run([os.environ.get("CLD_CODEX", "/home/para/work/codex-e2e/bin/codex"), "--version"], capture_output=True, text=True).stdout.strip() json.dump(d, open(sys.argv[1], "w"), indent=1) PY +} if [ "$KIND" = ours ]; then # ---- our port: the shape of the shipped profile rtx5090-32g.json and of the paired A/B jobs (decode/dt/jobs/speedtrain3-ab.sh), no bring-up tracing @@ -71,6 +73,7 @@ if [ "$KIND" = ours ]; then LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_DRAFT_VOCAB \ LELEKA_BRINGUP_TRACE LELEKA_PREFIX_TRACE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED if [ "$V" = V3 ]; then export LELEKA_ROUTE_TAIL_SKIP=7; EXPECT=on; else EXPECT=off; fi + write_stack_json { echo "variant=$V tag=$TAG"; date -u +%FT%TZ; free -g | sed -n 2p; uptime sha256sum "$E2E_BIN"/leleka-inference "$E2E_BIN"/leleka-daemon "$E2E_BIN"/leleka-cli "$E2E_BIN"/strata-next "$A/data/expert-profile.bin" cat "$ROOT/bin-main/COMMIT.txt" 2>/dev/null @@ -87,6 +90,7 @@ else cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/" unset STRATA_ROUTE_TAIL_SKIP STRATA_PREFILL_CPU_SHARE STRATA_DECODE_TIMING STRATA_VERIFY_PROFILE if [ "$V" = V2 ]; then export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; EXPECT=off; else EXPECT=on; fi + write_stack_json S=$HOME/work/vanilla-strata/control/bin/strata { echo "variant=$V tag=$TAG"; date -u +%FT%TZ; free -g | sed -n 2p; uptime sha256sum "$HOME/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata"; cat "$HOME/work/vanilla-strata/control/VERSION" "$HOME/work/vanilla-strata/control/COMMIT" 2>/dev/null From ff44dd606b860dbf3f6c54678e9ce4f1d796818e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 30 Oct 2026 23:35:27 +0100 Subject: [PATCH 04/10] e2e codex-delta: plan doc, matrix job generator, browser check helper Co-Authored-By: Claude Sonnet 5.5 --- docs/experiments/codex-lossy-delta.md | 87 ++++++++++++++++++++ scripts/e2e/codex/delta/browser_check_ttt.sh | 16 ++++ scripts/e2e/codex/delta/gen_jobs.py | 51 ++++++++++++ 3 files changed, 154 insertions(+) create mode 100644 docs/experiments/codex-lossy-delta.md create mode 100644 scripts/e2e/codex/delta/browser_check_ttt.sh create mode 100644 scripts/e2e/codex/delta/gen_jobs.py diff --git a/docs/experiments/codex-lossy-delta.md b/docs/experiments/codex-lossy-delta.md new file mode 100644 index 00000000..ece8e8ee --- /dev/null +++ b/docs/experiments/codex-lossy-delta.md @@ -0,0 +1,87 @@ +# Codex lossy-vs-lossless delta study (vanilla Strata 0.2.6 and our port, RTX 5090) + +Branch `claude/codex-lossy-delta` (from main `e1bd61f5`). Question of the owner: with the real Codex CLI on realistic tasks, how much worse is the +lossy mode (route tail skip) than the lossless one, for vanilla and for our port. The orchestrator judges the DELTA by re-reading the sessions: +"small" = the task still completes with less than 5 % extra agent rounds (rounds = model requests), "large" = 5 % or more extra rounds, or the +task fails where the lossless variant completes it. This page fixes the design; it contains no result. Numbers go to `runs/codex-lossy-delta/_index/`. + +## 1. Variants (same machine `rnr5090`, RTX 5090, 256k context, same model files, Codex CLI 0.163.0 sha256 `399ff69c...c4215`) + +| id | stack | setting | check before the first cell | +| --- | --- | --- | --- | +| V1 | vanilla Strata 0.2.6 (launcher `~/work/vanilla-strata/control`, engine 0.1.50 `ae49d5da...4776`, `launch --model iq3_s --context 256k --kv int8 --vision off --parallel 1 --tune skip`) | shipped defaults: `STRATA_ROUTE_TAIL_SKIP=7` ON by default, `STRATA_PREFILL_CPU_SHARE=auto` | engine.log has `STRATA_ROUTE_TAIL_SKIP=7 is ON (default)` (block.py stops the block otherwise) | +| V2 | same vanilla | `STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0` (both lossy defaults off, recorded in `stack.json`) | no `is ON` line; no `CPU share` line | +| V3 | our port, binaries `bin-main` = main `e1bd61f5` built in WSL (sha256 in `bin-main/COMMIT.txt`), `rtx5090-32g` profile shape (expert slots auto, GPU budget 32,819,404,800, spec-min-p 0, prefix cache auto/reply/8192, chain kernels, prompt-routing seed OFF, MTP draft vocabulary, ranked upstream expert profile `8f59b4aa...`) | `LELEKA_ROUTE_TAIL_SKIP=7` (EXPERIMENTAL, changes the output) | engine log (first decode) has `EXPERIMENTAL route tail skip is ON` | +| V4 | same binaries and shape | skip off (main default) | no such line | + +Vanilla runs untraced (no `STRATA_DECODE_TIMING`), ours with `LELEKA_SERVE_PROFILE=1` only (the per-request `expert tier ... route tail skip` line carries our skip counters). The ours shape is the one of the paired A/B jobs +(`decode/dt/jobs/speedtrain3-ab.sh`, `ours()`), run through the same `run-e2e.sh` as the earlier Codex jobs 943d/945d (copy in `run-e2e/`, state dir `codex-lossy-delta/w`). + +Sampling: Codex sends none. Vanilla would then use the model card's sampling (thinking: T 1.0, top_p 0.95, top_k 20) and ours is greedy. The logging proxy therefore +injects `"temperature": 0` into every `/v1/responses` request for ALL variants (greedy on both; recorded per request in `proxy/rounds.jsonl` as `fwd_sampling`). The proxy also maps the model name Codex sees (`qwen-local`, +identical in every variant, so Codex builds identical requests) to the engine's own id. The adaptive expert tier and the prefix cache are not bit-exact run to run, so greedy does not mean reproducible (measured by the pilot). + +## 2. What is captured, identically for the four stacks + +`scripts/e2e/codex/delta/logproxy.py` sits between Codex and the Responses endpoint of either stack. Per cell it writes `proxy/rounds.jsonl` (one line per HTTP request: timings, sizes, sha256, usage, output item summary) and, gzip-ed, every request body exactly as Codex +sent it, the forwarded body when the proxy changed it, and every response body exactly as received (`rounds/NNNN.{req.json,fwd.json,resp.sse}.gz`). Beside it: Codex's own rollout +(`codex-home/sessions/**/rollout-*.jsonl`), `codex-events.jsonl` (`codex exec --json` with arrival times), `codex.err`, the engine-log slice of the cell (`engine-slice.log`), the final workspace, `acceptance.log`, `cell.json`. The block directory +`V?/_stack-/` holds `inference.log` or `engine.log`, `strata-next.log`, `stack.json` (versions, env, warm-up, skip-state check, uptime, boot id), `mon.csv` (GPU temperature, clocks, power every 10 s), `memsample.txt`. +`delta/index.py` renders every session into `transcript.md` (round by round: new tool outputs, reasoning, calls, messages) and builds `_index/{index.csv,rounds.csv,index.md}`. + +Round = one POST `/responses` (counted by the proxy, retries and failed attempts included; completed and failed ones are listed separately). Codex's own tool-call count is in the index too. + +## 3. Tasks (`scripts/e2e/codex/tasks/`, frozen with `MANIFEST.sha256`, read-only on the server) + +| id | kind | what the agent does | acceptance (`accept.py`, exit 0 = done) | author's round estimate | +| --- | --- | --- | --- | --- | +| ttt | create | Three.js tic-tac-toe in one file (prompt of jobs 943*, unchanged) | STATIC checks on the server (file, relative import of the vendored three, WebGL renderer, raycaster, `#status`, `#restart`, win/draw logic, no network). The six real-click browser checks (`hidden/check_ttt.mjs`) need Node + Playwright, which the server lacks: run later over the stored workspaces and reported separately | 15-60 | +| crm | create | CRM web app, two phases (prompt of jobs 945*, unchanged) | 21 REST checks + the app's own tests (`hidden/crm_acceptance.py` on a copy) | 60-110 | +| fixbug-ledger | bugfix | 6 seeded bugs in a 12-module bookkeeping library, 133 tests, 13 fail | pristine tests untouched and green + 34 hidden behaviour tests | 15-40 | +| feature-query | feature | implement the `where` query language of `SPEC.md` for a small table store, CLI flag, tests, README | existing tests, ~250 hidden spec cases, the agent's >= 25 tests pass, README | 20-45 | +| refactor-shop | refactor | 8-step refactor of a 22-module legacy shop library by `REFACTOR.md`, 119 tests stay green | pristine tests (with the `Cust` rename) + 26 static and behaviour checks | 35-60 | +| debuglog-sched | debug | find the id-reuse bug of a job scheduler from a 4,730-line (417 KB) log, fix, regression test, `FINDINGS.md` | visible + regression tests, two hidden stress simulations (zero lost jobs), `FINDINGS.md` content | 20-50 | +| smoke-mini | bugfix | 2 bugs in a 120-line package; pipeline smoke only, not in the matrix | pristine tests + hidden cases | 6-14 | + +Every task has an exact prompt (between the marker lines of `task.md`), a seed workspace (copied byte for byte, digest `SEEDTREE` in the manifest, checked by `cell.py` before Codex starts), an acceptance script that does not know the variant, hidden files that never enter the workspace, and a reference +solution used only by `tasks/selftest.py` (acceptance FAILS on the bare seed and PASSES on seed + reference; verified for all 7 on Python 3.9 and 3.12, and it never modifies the workspace). The reference solutions are NOT installed on the server. The workspace Codex works in lives in +`codex-lossy-delta/_active/ws`, away from earlier results, and is moved into the cell afterwards. The Codex sandbox is `workspace-write` without network (`approval_policy = never`), as in the earlier jobs; it can still read the file system, which is a residual risk shared by all variants. +The Rust-crate idea of the owner's list was replaced by Python (the server has no Rust toolchain and the agent could not build); `gcc`/`make` exist but no C task was written. + +Limits, identical for all variants and cells: wall limit 2,400 s per cell, cap 150 model requests (the proxy answers 503 beyond it and the runner stops Codex; the cell is recorded as `round_cap`), Codex `model_reasoning_effort = medium`, `model_context_window = 262144`. +A cell that hits a limit counts as not completed, its rounds are the rounds it used. + +## 4. Order, repeats and the stack life + +One block = one stack start of one variant (model load: ours about 7-8 min, vanilla about 4-5 min) followed by several cells, so a cell does not pay a load. The engine therefore carries its expert-tier history and its prefix cache from one cell to the next +(Codex's first ~9k tokens are common to all tasks); this is identical for the four variants but means cells are not independent. The warm-up request before the first cell is the same for all. +Block order per repetition is a small balanced design that keeps the lossy/lossless pair of an engine adjacent and alternates which comes first: rep 1 V1 V2 V3 V4, rep 2 V2 V1 V4 V3, rep 3 V3 V4 V1 V2, rep 4 V4 V3 V2 V1; the task order inside a block rotates with the repetition. +Server drift (vanilla was 13.5-16 ms/round at uptime 11-13 h on 2026-10-29 and 10.1-11.7 ms/round after fresh boots) is recorded per block (`uptime_s_at_block`, `boot_id`, GPU clocks), not removed. + +## 5. GPU-hour estimate and the cut + +Per cell (lossless, 130 tok/s): ttt 4-15 min (943d: 203 s), crm 15-25 min (945d: 871 s), the four new tasks 6-20 min each (author estimates, unmeasured on this model). Per block: model load 5-8 min, shutdown 1 min, warm-up 1 min. + +| design | blocks | cell time per block | total | +| --- | --- | --- | --- | +| full: 6 tasks x 3 repeats x 4 variants | 12 | 65-130 min | 14-27 GPU-h | +| pilot + smoke (queued first): smoke-mini x1 + fixbug-ledger x2 per variant | 4 | 20-30 min | about 2 GPU-h | + +The full design exceeds the 10 h budget, so the matrix is cut AFTER the pilot, from measured cell times, by this rule: keep every task but give each cell the n that fits 8 GPU-h (pilot excluded): first drop CRM to n=1 per variant, then the long tasks to n=2, never below n=3 for the +short tasks (fixbug-ledger, ttt, feature-query) unless the pilot shows bit-identical repeats. What was cut is stated in the second report. + +## 6. What delta the data can resolve + +A 5 % difference of the mean round count is not resolvable with 2-3 repeats of agent sessions unless the sessions are reproducible. The index prints the measured run-to-run CV of the round count (same variant, same task) and the relative difference two cell means of n repeats can resolve +(`2.8 * CV * sqrt(2/n)`, two-sided alpha 0.05, power 0.8). With a CV of 25 % that is about 57 % at n=3 for one task, about 23 % when the six tasks are pooled; with sessions that repeat exactly the per-cell delta is exact but is a statement about one trajectory. The index therefore reports, for each task, the lossy +and lossless round counts of every repeat, the paired difference by repeat, the completion counts, and the first round where the lossy and lossless sessions differ (with transcript line numbers), so the orchestrator can read both the numbers and the sessions. No quality verdict is computed. + +## 7. How to run and read + +```sh +bash scripts/e2e/codex/delta/install.sh # laptop: freeze + check + install on the server (read-only), nothing is hard-deleted +# server: stub ~/work/gpu-runs/holder2/jobs/.sh = `exec bash /data/leleka-e2e/codex-lossy-delta/delta/jobs/.sh`, add to jobs/PRIORITY +python3 -I ~/work/leleka/codex-lossy-delta/delta/index.py ~/work/leleka/runs/codex-lossy-delta # index.csv, rounds.csv, index.md, transcripts +``` + +Layout: `~/work/leleka/runs/codex-lossy-delta//-r/` (matrix cells), `_smoke/V?/...` (smoke), `V?/_stack-/` (stack logs), `_index/`. Incomplete cells are renamed `*.incomplete-