Skip to content

fix(common/time_utils): correct None/empty timestamp fallback and ISO 8601 parsing - #16173

Closed
Harsh23Kashyap wants to merge 0 commit into
infiniflow:mainfrom
Harsh23Kashyap:Harsh23Kashyap/fix/time-utils-edgecases
Closed

Harsh23Kashyap wants to merge 0 commit into
infiniflow:mainfrom
Harsh23Kashyap:Harsh23Kashyap/fix/time-utils-edgecases

Conversation

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Fixes two correctness bugs in common/time_utils.py:

  1. timestamp_to_date(None) / timestamp_to_date("") returned a date near 1970 instead of the current time because the fallback used time.time() (seconds) and then divided by 1000 again.
  2. format_iso_8601_to_ymd_hms validated with dateutil.isoparse but then re-parsed with stricter datetime.fromisoformat, so ordinal ISO dates like 2024-001T12:00:00Z were returned unconverted.

This change uses current_timestamp() for the fallback and normalizes timestamps by parsing once with dateutil.isoparse. It also adds regression tests for None/empty fallback handling and ordinal ISO date parsing.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

AI-assistance disclosure: parts of this change (bug triage and test scaffolding) were drafted with AI assistance and fully reviewed and verified by me.

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Jun 18, 2026
@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Thanks for reviewing! Could a maintainer please add the \ label so the full test workflow runs on this non-draft PR?

@dosubot dosubot Bot added 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jun 18, 2026
@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Follow-up: please add the ci label to trigger the full CI workflow for this PR. Thanks!

@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
common/time_utils.py (1)

49-51: ⚡ Quick win

Add logging for the new fallback branch.

The new “empty input → current timestamp” path is a behavior branch and should emit a debug log for observability.

💡 Proposed fix
 def timestamp_to_date(timestamp, format_string="%Y-%m-%d %H:%M:%S"):
@@
-    if not timestamp:
+    if not timestamp:
+        logging.debug("timestamp_to_date received empty timestamp; using current_timestamp() fallback")
         timestamp = current_timestamp()

As per coding guidelines, "**/*.py: Add logging for new flows".

🤖 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 `@common/time_utils.py` around lines 49 - 51, The fallback branch in the
timestamp handling (the `if not timestamp:` condition where
`current_timestamp()` is called) lacks logging for observability. Add a debug
log statement inside this conditional block after the `timestamp =
current_timestamp()` assignment to log that the fallback to current timestamp
occurred, ensuring the new flow path is observable for debugging and monitoring
purposes.

Source: Coding guidelines

test/unit_test/common/test_time_utils.py (1)

656-708: ⚡ Quick win

Add required priority markers to the new pytest classes.

Please tag these new regression classes with a priority marker (p1/p2/p3) to match test-selection conventions.

💡 Proposed fix
+@pytest.mark.p1
 class TestTimestampToDateCurrentTimeFallback:
@@
+@pytest.mark.p1
 class TestFormatIso8601ToYmdHms:

As per coding guidelines, "test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python testing".

🤖 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 `@test/unit_test/common/test_time_utils.py` around lines 656 - 708, The new
test classes TestTimestampToDateCurrentTimeFallback and
TestFormatIso8601ToYmdHms are missing required pytest priority markers. Add a
pytest marker decorator (using p1, p2, or p3) above each of these class
definitions to indicate their priority level and match the test-selection
conventions used throughout the test suite. Choose an appropriate priority level
based on the importance and scope of each test class.

Source: Coding guidelines

🤖 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 `@common/time_utils.py`:
- Around line 49-51: In the `timestamp_to_date` function, the condition `if not
timestamp:` incorrectly treats the value 0 as missing input because 0 is falsy
in Python, causing valid epoch-millisecond timestamps to be silently replaced
with the current timestamp. Replace the condition `if not timestamp:` with `if
timestamp is None:` to explicitly check for None instead of relying on falsy
evaluation, allowing 0 to be properly treated as a valid timestamp input.

---

Nitpick comments:
In `@common/time_utils.py`:
- Around line 49-51: The fallback branch in the timestamp handling (the `if not
timestamp:` condition where `current_timestamp()` is called) lacks logging for
observability. Add a debug log statement inside this conditional block after the
`timestamp = current_timestamp()` assignment to log that the fallback to current
timestamp occurred, ensuring the new flow path is observable for debugging and
monitoring purposes.

In `@test/unit_test/common/test_time_utils.py`:
- Around line 656-708: The new test classes
TestTimestampToDateCurrentTimeFallback and TestFormatIso8601ToYmdHms are missing
required pytest priority markers. Add a pytest marker decorator (using p1, p2,
or p3) above each of these class definitions to indicate their priority level
and match the test-selection conventions used throughout the test suite. Choose
an appropriate priority level based on the importance and scope of each test
class.
🪄 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

Run ID: e3c6011d-3023-4235-a5ae-54d9ed8c881e

📥 Commits

Reviewing files that changed from the base of the PR and between a9ddcae and cef5571.

📒 Files selected for processing (2)
  • common/time_utils.py
  • test/unit_test/common/test_time_utils.py

Comment thread common/time_utils.py Resolved
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 18, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/unit_test/common/test_time_utils.py (1)

667-681: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make current-time fallback assertions deterministic to avoid CI flakes.

These tests rely on real wall-clock bounds (±2s), which can intermittently fail under scheduler pauses. Mock common.time_utils.current_timestamp to a fixed millisecond value and assert exact output instead.

💡 Proposed deterministic test update
 class TestTimestampToDateCurrentTimeFallback:
@@
-    def test_none_uses_current_time(self):
-        """None input must resolve to the current time, not the epoch."""
-        before = time.time()
-        result = timestamp_to_date(None)
-        after = time.time()
-        parsed = time.mktime(time.strptime(result, "%Y-%m-%d %H:%M:%S"))
-        assert before - 2 <= parsed <= after + 2
+    def test_none_uses_current_time(self, monkeypatch):
+        """None input must resolve to current_timestamp() fallback."""
+        fixed_ms = 1704067200123
+        monkeypatch.setattr("common.time_utils.current_timestamp", lambda: fixed_ms)
+        assert timestamp_to_date(None) == time.strftime(
+            "%Y-%m-%d %H:%M:%S", time.localtime(fixed_ms / 1000)
+        )
@@
-    def test_empty_string_uses_current_time(self):
-        """Empty-string input must resolve to the current time, not the epoch."""
-        before = time.time()
-        result = timestamp_to_date("")
-        after = time.time()
-        parsed = time.mktime(time.strptime(result, "%Y-%m-%d %H:%M:%S"))
-        assert before - 2 <= parsed <= after + 2
+    def test_empty_string_uses_current_time(self, monkeypatch):
+        """Empty-string input must resolve to current_timestamp() fallback."""
+        fixed_ms = 1704067200123
+        monkeypatch.setattr("common.time_utils.current_timestamp", lambda: fixed_ms)
+        assert timestamp_to_date("") == time.strftime(
+            "%Y-%m-%d %H:%M:%S", time.localtime(fixed_ms / 1000)
+        )
🤖 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 `@test/unit_test/common/test_time_utils.py` around lines 667 - 681, The test
methods test_none_uses_current_time and test_empty_string_uses_current_time are
using real wall-clock time boundaries with ±2 second tolerances to verify that
timestamp_to_date handles None and empty string inputs by returning the current
time, but this approach is flaky under scheduler pauses. Mock the
current_timestamp function from common.time_utils to return a fixed millisecond
value, then update both test assertions to compare the result of
timestamp_to_date against the exact expected output derived from the mocked
timestamp rather than comparing against before/after time ranges. This makes the
tests deterministic and eliminates timing-dependent failures.
🤖 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.

Outside diff comments:
In `@test/unit_test/common/test_time_utils.py`:
- Around line 667-681: The test methods test_none_uses_current_time and
test_empty_string_uses_current_time are using real wall-clock time boundaries
with ±2 second tolerances to verify that timestamp_to_date handles None and
empty string inputs by returning the current time, but this approach is flaky
under scheduler pauses. Mock the current_timestamp function from
common.time_utils to return a fixed millisecond value, then update both test
assertions to compare the result of timestamp_to_date against the exact expected
output derived from the mocked timestamp rather than comparing against
before/after time ranges. This makes the tests deterministic and eliminates
timing-dependent failures.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 10fc9ff3-86eb-4fcd-81ef-56354bae0857

📥 Commits

Reviewing files that changed from the base of the PR and between cef5571 and 4dc0547.

📒 Files selected for processing (2)
  • common/time_utils.py
  • test/unit_test/common/test_time_utils.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • common/time_utils.py

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Addressed the CodeRabbit flakiness feedback in the latest commit by making fallback assertions deterministic via current_timestamp monkeypatching (no wall-clock tolerance windows).

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Friendly follow-up: could a maintainer please add the ci label so the full test workflows run on this PR? Thank you!

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Hi maintainers, quick follow-up on this one. The PR is non-draft and mergeable, but the test workflow is still skipped without the ci label. Could you please add the label when you get a chance?

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Quick update: this PR remains focused on the timestamp/ISO parsing fix and deterministic fallback tests. I can make any additional adjustments quickly if maintainers prefer a different shape; would appreciate a review when possible.

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Hi maintainers — please look into this when you have a chance. Happy to adjust if anything needs changing.

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Hi maintainers, this is ready for review when you have a chance. Happy to adjust if anything needs changing.

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Hi maintainers, this branch is current and CodeRabbit is passing. Could you add the ci label when convenient so the full workflows can run?

1 similar comment
@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

Hi maintainers, this branch is current and CodeRabbit is passing. Could you add the ci label when convenient so the full workflows can run?

@yuzhichang
yuzhichang force-pushed the main branch 2 times, most recently from 78db4e9 to f86a0e7 Compare June 29, 2026 01:47
@yuzhichang yuzhichang closed this Jun 29, 2026
@yuzhichang
yuzhichang force-pushed the Harsh23Kashyap/fix/time-utils-edgecases branch from a2801e2 to 6e82e27 Compare June 29, 2026 06:24
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jun 29, 2026
@yuzhichang

Copy link
Copy Markdown
Member

This PR was closed after its branch was accidentally moved to the wrong commit (6e82e2726df6aa0a9139c5d42fc0def4cce50461, from upstream/main) during the rewrite-cleanup work. I rebuilt the intended branch locally on top of current upstream/main, and the correct replacement commit chain is:

  • 34fe53fcf fix(common/time_utils): correct fallback timestamp and ISO-8601 normalization
  • 900edeaba fix(common/time_utils): preserve zero timestamps and mark regression tests
  • f42ca0781 test(common/time_utils): make fallback assertions deterministic

I attempted to restore the PR directly, but GitHub currently blocks both recovery steps from my side:

  • maintainerCanModify is false, so I cannot force-push the repaired branch back to Harsh23Kashyap/fix/time-utils-edgecases
  • reopening the PR is also rejected because GitHub sees no new commits on the fork branch in its current state

The shortest recovery path is:

  1. move Harsh23Kashyap/fix/time-utils-edgecases to the rebuilt chain above (or cherry-pick those 3 commits onto a fresh branch from current upstream/main and force-push it to that branch name)
  2. reopen this PR

Once the branch points at that rebuilt chain, the PR should be recoverable normally.

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator Author

@yuzhichang Thanks for the recovery notes. I cherry-picked the three commits onto current upstream/main and force-pushed Harsh23Kashyap/fix/time-utils-edgecases (f6bfbaa9). GitHub would not reopen #16173 while the PR head was stuck at the accidental 6e82e27 snapshot, so I opened recovery PR #16483 from the same branch. Happy to close #16483 and reopen this one if you can trigger that from your side.

yuzhichang pushed a commit that referenced this pull request Jun 30, 2026
… 8601 parsing (#16483)

Recovery PR for #16173 after the fork branch was accidentally reset
during rewrite-cleanup.

Cherry-picked onto current `main`:
- fix(common/time_utils): correct fallback timestamp and ISO-8601
normalization
- fix(common/time_utils): preserve zero timestamps and mark regression
tests
- test(common/time_utils): make fallback assertions deterministic

Supersedes closed #16173 — same branch
`Harsh23Kashyap/fix/time-utils-edgecases`, rebuilt per @yuzhichang
recovery steps in
#16173 (comment)

---------

Co-authored-by: Harsh Kashyap <[email protected]>
Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. size:XS This PR changes 0-9 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants