Skip to content

BrainAPI is a knowledge graph–powered AI memory layer that transforms unstructured data into structured knowledge, enabling intelligent search, recommendations, and contextual memory for AI agents and applications.

fix: use calendar.isleap() for correct Gregorian leap year check in _shift_months

Shrey Tiwari50abe3652f8e
diff --git a/src/utils/dates.py b/src/utils/dates.py
index d3ed852..dcbad1f 100644
--- a/src/utils/dates.py
+++ b/src/utils/dates.py
@@ -1,3 +1,4 @@
+import calendar
from datetime import datetime, timedelta, timezone
from typing import Optional
import re
@@ -64,7 +65,7 @@ def _shift_months(ref: datetime, delta: int) -> datetime:
month = ref.month - 1 + delta
year = ref.year + month // 12
month = month % 12 + 1
- day = min(ref.day, [31, 29 if year % 4 == 0 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
+ day = min(ref.day, [31, 29 if calendar.isleap(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
return ref.replace(year=year, month=month, day=day)
diff --git a/tests/test_dates.py b/tests/test_dates.py
index aaf622a..eaf1ea9 100644
--- a/tests/test_dates.py
+++ b/tests/test_dates.py
@@ -151,6 +151,18 @@ class ResolveRelativeDateTests(unittest.TestCase):
"yesterday",
)
+ def test_next_month_on_century_non_leap_year_does_not_crash(self):
+ self.assertEqual(
+ resolve_relative_date("next month", "2100-01-31"),
+ "28/02/2100",
+ )
+
+ def test_last_month_on_century_non_leap_year_does_not_crash(self):
+ self.assertEqual(
+ resolve_relative_date("last month", "2100-03-31"),
+ "28/02/2100",
+ )
+
class ToNaiveUtcTests(unittest.TestCase):
def test_naive_value_is_returned_unchanged(self):