Skip to content

DAT-1243 Retail Calendar port to Python - #1

Merged
abuyukcakir merged 4 commits into
masterfrom
feature/DAT-993/retail-calendar-port-to-python
Oct 12, 2026
Merged

abuyukcakir merged 4 commits into
masterfrom
feature/DAT-993/retail-calendar-port-to-python

Conversation

@abuyukcakir

@abuyukcakir abuyukcakir commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

https://linear.app/toolio/issue/DAT-1243/port-retail-calendar-to-retail-calendar-python

A Python port of the retail-calendar npm package (v4.1.2), so toolio-ml can do retail-calendar date conversions in-process instead of calling retail-calendar-api over HTTP.

  • No dependencies outside the standard library, like the JS package. Python 3.14+.
  • Same enum integer values and labels as the JS package, the calendarconfiguration table and retail-calendar-api, so tenant configs work as they are (RetailCalendarOptions.from_dict(row) reads DB rows and API payloads directly).
  • Calendar output matches the JS package exactly (see Parity below).

What's included

Module Contents
enums.py WeekGrouping, LastDayOfWeek, LastMonthOfYear, WeekCalculation as IntEnums with the JS values, plus .label / from_label() for DB and API strings ("4-4-5", "Saturday", "lastDayNearestEndOfMonth")
options.py RetailCalendarOptions (frozen, hashable, validated), from_dict / to_dict, NRF_CALENDAR_OPTIONS
strategies.py The six year-end strategies, ported one to one
calendar.py RetailCalendar (weeks, months, days built on first access) and the cached get_retail_calendar()
lookup.py week_of_gregorian_date, plus date_to_segment / segment_to_date / leap_years, which mirror the retail-calendar-api endpoints
scripts/golden/ Node scripts that generate and check reference data from the pinned npm package

Tooling: uv, ruff, mypy --strict, pytest with 100% line and branch coverage, Hypothesis, pre-commit and GitHub Actions. The README has a JS-to-Python name table and a note telling contributors and agents to keep both repos in sync.

Parity with the JS package

tests/test_golden.py compares against reference data from retail-calendar@4.1.2 running in UTC:

  • year boundaries for every strategy × week-end day × year-end month, 1950–2060 (about 47k calendars)
  • every week, month and day of 576 configurations (all strategies, groupings and leap-week options), 2000–2050, compared by hash, with full detail for 2023
  • 20,000 random date-to-week lookups through weekOfGregorianDate

Everything matches. All JS test cases are ported as well.

CI regenerates the reference data from npm with scripts/golden/check.sh and fails if it differs from what's committed. The check compares decompressed contents, because gzip headers record the OS that wrote them, so the .gz bytes differ between macOS and Linux even when the data is identical.

Intentional differences from the JS package

  • Dates are datetime.date, with inclusive ends. The JS returns Date objects that end at 23:59:59.999.
  • The 53rd week uses None instead of -1 for its month and quarter fields.
  • Validation is strict. Unknown labels, addLeapWeekToMonth outside 0–11, missing custom leap year options and unsupported years (outside 2–9997) raise ValueError straight away. The JS fails later or silently gives wrong results.
  • No timezone effects. Python works on plain dates, so it always matches the JS running in UTC (see caveat 1).
  • Calendars and options are immutable, so the shared cache is safe.

Caveats to discuss with Cihan // @cihancimen

  1. The JS output depends on the host timezone. I ran 21,420 calendars (5 strategies × 7 week-end days × 12 months × 1990–2040) in other timezones. Compared with UTC, 9 differ in New York, 38 in Sydney and 54 in Istanbul. Example: LastDayNearestEOM, weeks ending Sunday, year ending October, 2012 has 53 weeks in UTC but 52 in New York. The cause is local-time Date math floored to whole days across DST changes.

    • This port treats UTC as correct. Can we confirm retail-calendar-api runs in UTC in production (no WEBSITE_TIME_ZONE override)?
    • Does anything run the JS package in a browser or a non-UTC server (frontend, holonk)?
    • Should the JS package switch to UTC date math?
  2. LastDayBeforeEomExceptLeapYear only works for years ending in December. It takes endOfYear(...) (Dec 31) as next year's end instead of the same month a year later. For any other month it behaves exactly like LastDayBeforeEOM; I verified this for January and August year-ends. The port copies the bug for parity. Fix it in both, or document it as December-only?

  3. PenultimateDayOfWeekNearestEOM checks lastDayOfIsoWeek === 0, which never happens with ISO days 1–7; it should be === 1 (Monday). The results are still correct, so this is only cleanup. The Python version uses the correct check and matches the JS everywhere.

  4. CustomLeapYear ignores lastDayOfWeek. If leapYearEndDate isn't on that weekday, weeks silently end on a different day. Should both packages reject such configs? We'd first need to check the existing tenant configs.

  5. The JS package accepts invalid input silently:

    • an addLeapWeekToMonth above 11 drops the 53rd week without an error;
    • a lastMonthOfYear above 11 rolls over into the next year;
    • unknown enum values make the strategy lookup return undefined.

    Python raises instead. Should the JS validate the same way?

  6. JS memoization hands out shared, mutable calendar objects, and its cache key depends on the order of option keys.

  7. retail-calendar-api: in calendar-service.js, unknown labels are meant to fall back to defaults, but WeekCalculation, WeekGrouping, LastDayOfWeek and LastMonthOfYear aren't imported there. Those requests throw a ReferenceError instead.

  8. A JS test fixture has malformed dates. About 100 dates in __tests__/data/last_day_nearest_eom_445_arbitrary_leap_year_weeks.ts contain stray spaces ("2024-01 -08", "2024 -08-04"). The JS test parser tolerates them; they're fixed in this repo's copy.

  9. The JS repo's LICENSE names "Fatih Kadir Akın", who never committed to it. It looks copied from another project. This repo's LICENSE says Toolio.

  10. Keeping the repos in sync: who releases the JS package and bumps the pin in scripts/golden/package.json when calendar behavior changes? The README spells out the steps.

Out of scope / follow-ups

  • toolio-ml integration: replace the retail-calendar-api calls in TemporalDateUtility and add pandas helpers there, so the per-row loop becomes a vectorized lookup (about 0.5 s for 1M rows in a prototype). The pandas helpers stay out of this repo to keep it dependency-free.
  • Distribution: the README assumes a git tag dependency (retail-calendar @ git+ssh://…@v1.0.0). Azure Artifacts and a Databricks wheel are the alternatives.
  • toolio-ml still allows Python 3.11 (Databricks DBR 15.4), and this package requires 3.14. Any Databricks job still on 3.11 won't be able to install it.

Testing

uv sync
uv run pytest -n auto   # 164 tests, about 30 s
uv run ruff check . && uv run ruff format --check . && uv run mypy

To regenerate the reference data: cd scripts/golden && npm ci && npm run generate. To only check it: ./check.sh.

🤖 Generated with Claude Code

https://claude.ai/code/session_01GaY7VR1MJXPdTtk1WjfoK2

@abuyukcakir
abuyukcakir requested a review from cihancimen October 8, 2026 13:48
@abuyukcakir abuyukcakir self-assigned this Oct 8, 2026
@linear-code

linear-code Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
DAT-993 Add partitioning to ACG metrics table

  • Give the Issue a title (above)

  • Set the Priority

    For urgent issues you can ping the Customer Support channel

  • Labels

    • Make sure the ticket has the Performance label
    • Select one of the module labels to specify the impacted module
    • Select one of the module labels to specify the impacted customer
  • Don't Change: Status, Assignee, Estimate, Cycle, Project

Please fill out the below fields:

  • Issue Time (with UTC timezone):

  • View Name:

  • Link to View:

  • Link to Video:

  • Operation Description: Check response times for ACG metrics for the Nordstrom tenant and determine whether partitioning automatedclustergroupmetrics is needed. The table has 176,170,366 rows for Nordstrom and is currently unpartitioned.

    cc: @aitor

  • Operation Duration Estimates:

    • Baseline: (e.g. expected duration 15 seconds)
    • Actual: (e.g. 120 seconds)

@alican s notes:

  • Need to understand whether we need partitioning in the automatedclustergroupmetrics table. Reasons:
    • The bottom panel for the metrics takes a long while to open
    • Copying the prod db to dev is slower due to not having partition here.

DAT-1243 Port retail-calendar to retail-calendar-python

Completely port retail-calendar to retail-calendar-python.

Review in Linear

@abuyukcakir abuyukcakir changed the title DAT-993 Retail Calendar port to Python DAT-1243 Retail Calendar port to Python Oct 8, 2026
@cihancimen

Copy link
Copy Markdown
Collaborator

Thanks for this, it is very thorough. I ran the port against the JS (4.1.2, UTC) on all 351 weekly/daily calendar configs we have in prod (146 tenants, including the customLeapYear ones), 2015-2035. 384,639 weeks compared, 0 differences.

One change I'd like before toolio-ml depends on it:

  • requires-python = ">=3.14" blocks toolio-ml on Databricks (3.11). Nothing in the code needs 3.14. I lowered it to >=3.11 in a scratch copy and all 164 tests pass on 3.11 and 3.12. Could you set it to >=3.11, set mypy python_version to 3.11 and add 3.11 to the CI matrix?

Smaller things:

  • 81 prod configs are Monthly with no week method/grouping/weekday. from_dict raises on them, which is correct, but toolio-ml has to filter to Weekly/Daily first. Probably worth a line in the README.
  • retail-calendar is not registered on PyPI. A plain pip install retail-calendar would pull whatever someone publishes there. We should either reserve the name or rename to something like toolio-retail-calendar.

Answers to the caveats:

  1. Timezone:
    • retail-calendar-api runs in UTC. Checked on the container (date shows UTC, TZ is empty). Also FYI: dev-retail-calendar-api is effectively prod, prod-toolio-api-mcp and toolio-ml prod both point to it.
    • holonk and toolio-api-mcp also use the package server side without a TZ, so UTC too. toolio-frontend builds calendars in the browser with the user's local TZ and no normalization.
    • I ran our real configs (2015-2035) in a few timezones. New York and LA: 0 differences. Istanbul: 5 configs, only 2015-16. Sydney: 2 configs (altitudesports). London: altitudesports "Daily Calendar" differs in 2026 and 2027. Altitude Sports is in Montreal so probably no one sees it.
    • So yes, the JS should switch to UTC math. It is a no-op for US browsers. Not urgent.
  2. All 5 prod configs using lastDayBeforeEndOfMonthExceptLeapYear end in December, so nobody hits this. I'd document it as December-only and reject other months in both packages instead of fixing it.
  3. Agreed, just cleanup. Can go in with the next JS change.
  4. All 14 customLeapYear configs with an end date land on their lastDayOfTheWeek. Rejecting mismatches won't break anyone. Separately, 3 customLeapYear configs are broken in both JS and Python (leapYear null): fabfitfun "CalendarFix", chrisyoung "F3_Testing_20260116", demo "Test 2". fabfitfun is a real tenant, we should check if that one is used.
  5. DB rows can't produce these. All fields are MySQL enums, and addLeapWeekToMonth is tinyint unsigned (prod only has 0, 9, 11). Only direct API callers can hit it. Nice to have.
  6. Agreed, nothing to do for the port.
  7. Confirmed, it only triggers on unknown labels, which the DB can't produce. It is a one line import fix, I can do it.
  8. 👍
  9. That was me, the repo wasn't forked. Probably copied from a starter template in 2020. Both the repo and the npm package are public, so I'll fix it.
  10. Whoever changes the calendar behavior does both sides, as the README describes.

@abuyukcakir

Copy link
Copy Markdown
Collaborator Author

Thanks @cihancimen, running it against all 351 prod configs is exactly the check I hoped for. 384,639 weeks with 0 differences is reassuring.

Done in 7ba5462:

  • requires-python = ">=3.11", mypy and ruff now target 3.11, and CI tests 3.11, 3.12, 3.13 and 3.14. Lint and the wheel install check run on 3.11. I also put from __future__ import annotations back in every module, with ruff enforcing it, since 3.11 evaluates annotations eagerly.
  • README: Monthly configs make from_dict raise, so toolio-ml has to filter on granularity first.

Later:

  • PyPI name: agreed it's a risk. We'll decide between reserving retail-calendar and renaming to something like toolio-retail-calendar separately. Until then, installs go through the git URL, which never looks at PyPI.

Follow-ups from your caveat answers:

  • (2) and (4): I'll add both checks in one follow-up that covers both repos, so the packages never disagree. One rejects lastDayBeforeEndOfMonthExceptLeapYear unless the year ends in December (and the docs will say December-only); the other rejects custom-leap-year configs whose end date isn't on lastDayOfTheWeek. Good to know no prod config breaks.
  • (1) UTC math in the JS package: follow-up, not urgent, as you said. It only changes anything for non-US browsers in toolio-frontend.
  • (3) The penultimate === 0 cleanup: with the next JS change.
  • (7) The calendar-service.js import fix, and (9) the JS LICENSE: thanks for taking those.
  • The 3 custom-leap-year configs with leapYear null: do you know who can check whether fabfitfun's "CalendarFix" is still used?

@abuyukcakir
abuyukcakir merged commit 5fa9cfa into master Oct 12, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants