Skip to content

fix: use timezone-aware memory timestamps#5918

Open
Ghraven wants to merge 2 commits into
crewAIInc:mainfrom
Ghraven:fix/memory-timezone-aware-utc
Open

fix: use timezone-aware memory timestamps#5918
Ghraven wants to merge 2 commits into
crewAIInc:mainfrom
Ghraven:fix/memory-timezone-aware-utc

Conversation

@Ghraven
Copy link
Copy Markdown

@Ghraven Ghraven commented May 24, 2026

Summary

  • replace remaining naive datetime.utcnow() calls in the unified memory runtime with timezone-aware UTC timestamps
  • update the matching memory tests to construct timezone-aware UTC datetimes

Before / after

Before, memory records and LanceDB rows could be created or scored with naive UTC datetimes from datetime.utcnow().
After, these code paths use datetime.now(timezone.utc), preserving explicit UTC offsets in serialized timestamps.

Verification

  • python -m py_compile lib/crewai/src/crewai/memory/unified_memory.py lib/crewai/src/crewai/memory/types.py lib/crewai/src/crewai/memory/encoding_flow.py lib/crewai/src/crewai/memory/storage/lancedb_storage.py lib/crewai/tests/memory/test_unified_memory.py
  • git diff --check

Summary by CodeRabbit

  • Bug Fixes

    • Standardized timestamps to use timezone-aware UTC across memory operations, improving accuracy and consistency of time-based behavior and scoring; maintains compatibility with legacy naive timestamps.
  • Tests

    • Updated memory test suite to reflect timezone-aware timestamp handling and added a test ensuring legacy naive datetimes remain supported.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 24, 2026

📝 Walkthrough

Walkthrough

This PR migrates the memory module from naive UTC datetimes to timezone-aware UTC timestamps. All datetime creation and recency calculations use datetime.now(timezone.utc) with a helper to normalize legacy naive datetimes; tests and LanceDB storage touch/schema timestamps were updated accordingly.

Changes

Timezone-aware UTC timestamp migration

Layer / File(s) Summary
LanceDB storage layer updates
lib/crewai/src/crewai/memory/storage/lancedb_storage.py
LanceDB storage backend now imports timezone and uses datetime.now(timezone.utc) for schema placeholder timestamps, parsing fallbacks when values are missing, and touch_records write operations.
Memory scoring and API updates
lib/crewai/src/crewai/memory/types.py, lib/crewai/src/crewai/memory/unified_memory.py, lib/crewai/src/crewai/memory/encoding_flow.py
Added _as_utc helper and updated compute_composite_score to compute ages against datetime.now(timezone.utc); Memory.update() and the encoding flow now write last_accessed using timezone-aware UTC.
Test suite alignment
lib/crewai/tests/memory/test_unified_memory.py
Composite-scoring tests updated to construct timezone-aware created_at values and a new test ensures legacy naive created_at=datetime.utcnow() records are still accepted.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through timestamps, snug and neat,

replaced the naive with UTC complete.
Old memories score, both new and shy,
now timezone-aware beneath the sky.
A tiny hop to keep time spry.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: use timezone-aware memory timestamps' directly and clearly describes the main change: converting naive UTC datetimes to timezone-aware UTC timestamps across memory system files.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/crewai/src/crewai/memory/types.py`:
- Line 371: compute_composite_score is subtracting datetime.now(timezone.utc)
from MemoryRecord.created_at which can be naive (datetime.utcnow) causing a
TypeError; update the score computation to normalize record timestamps to
timezone-aware UTC before subtraction (e.g., detect if record.created_at or
record.last_accessed is tzinfo is None and convert to UTC-aware via
replace(tzinfo=timezone.utc) or astimezone(timezone.utc)), and apply the same
normalization wherever created_at/last_accessed are used so all datetime
arithmetic in compute_composite_score and related functions operates on
consistent UTC-aware datetimes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b764b9ac-76be-48d8-b702-e3a4a84c8b81

📥 Commits

Reviewing files that changed from the base of the PR and between c3e2001 and bba98de.

📒 Files selected for processing (5)
  • lib/crewai/src/crewai/memory/encoding_flow.py
  • lib/crewai/src/crewai/memory/storage/lancedb_storage.py
  • lib/crewai/src/crewai/memory/types.py
  • lib/crewai/src/crewai/memory/unified_memory.py
  • lib/crewai/tests/memory/test_unified_memory.py

Comment thread lib/crewai/src/crewai/memory/types.py Outdated
@Ghraven
Copy link
Copy Markdown
Author

Ghraven commented May 24, 2026

Thanks for catching this. I pushed a small follow-up that normalizes legacy naive datetimes to UTC before the recency calculation, and added a regression test for that path.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lib/crewai/src/crewai/memory/types.py (1)

352-356: 💤 Low value

Consider adding a docstring to document the UTC assumption.

The _as_utc() helper correctly normalizes naive and tz-aware datetimes to UTC, preventing TypeErrors in datetime arithmetic. The implementation assumes naive datetimes are in UTC, which is valid given the codebase context (legacy timestamps used datetime.utcnow()).

📝 Suggested docstring
 def _as_utc(dt: datetime) -> datetime:
+    """Normalize a datetime to timezone-aware UTC.
+    
+    Naive datetimes are assumed to be in UTC and have tzinfo added.
+    Timezone-aware datetimes are converted to UTC.
+    
+    Args:
+        dt: A naive or timezone-aware datetime.
+    
+    Returns:
+        A timezone-aware datetime in UTC.
+    """
     if dt.tzinfo is None:
         return dt.replace(tzinfo=timezone.utc)
     return dt.astimezone(timezone.utc)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/crewai/src/crewai/memory/types.py` around lines 352 - 356, Add a short
docstring to the helper function _as_utc() explaining that it normalizes naive
and tz-aware datetimes to UTC and that naive datetimes are assumed to already be
UTC (matching legacy usage like datetime.utcnow()); include expected input types
and returned datetime timezone behavior so callers know this normalization
occurs and no timezone conversion is attempted for naive datetimes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@lib/crewai/src/crewai/memory/types.py`:
- Around line 352-356: Add a short docstring to the helper function _as_utc()
explaining that it normalizes naive and tz-aware datetimes to UTC and that naive
datetimes are assumed to already be UTC (matching legacy usage like
datetime.utcnow()); include expected input types and returned datetime timezone
behavior so callers know this normalization occurs and no timezone conversion is
attempted for naive datetimes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e3767868-2f60-452e-bbbb-3d1925b58863

📥 Commits

Reviewing files that changed from the base of the PR and between bba98de and 90d6dff.

📒 Files selected for processing (2)
  • lib/crewai/src/crewai/memory/types.py
  • lib/crewai/tests/memory/test_unified_memory.py

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.

1 participant